SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Boredom comes to those
who wait
Asynchronous calls to Datastore Plus
What you should know
•toplevels/tasklets

•futures

•yield (you are going to build lots of generators)

•you'll use yield instead of return (most of the time)

•don't think about threads

•..._async

•the query API changes

•an insanely great use for comparator overrides
How it used to be done

class Fact(model.Model):
    text = model.TextProperty()
    rating = model.FloatProperty(default = 400.)
    random_index = model.ComputedProperty(
        lambda self : random.randint(0,
            sys.maxint))
(...)
for i in range(10):
    Fact(text = 'Fact %d' % i).put()
Digression: _ah/stats

•A good way to understand the performance of your apps

•If you are doing something wrong, it'll become obvious



Easy to enable on app.yaml:



builtins:
(...)
- appstats: on
How the first example
behaves locally
… and on the server
The asynchronous way

futures = []
for i in range(10):
    futures.append(Fact(text = 'Fact %d' % 

        i).put_async())
[ f.get_result() for f in futures ]

 

Gives the opportunity to aggregate puts into one large datastore
operation (and we don't have to worry about it)
_ah/stats
On the server
Better: toplevel/tasklet
@context.toplevel
(decorating something – usually a request handler – that will call the following tasklet)

 

@tasklets.tasklet
def init_facts()
  futures = []
  for i in range(10):
    futures.append(Fact(text = 'Fact %d' % 
      i).put_async())
  yield futures
 

Yield allows the toplevel event loop to manage other generators making asynchronous calls
… even better
@context.toplevel
(decorating your handler)



@tasklets.tasklet
def init_facts()
     Futures = []
     for i in range(10):
           futures.append(Fact(text = 'Fact %d' 
                 % i).put_async())
     raise tasklets.Return(futures)
Because it's considered polite to raise things when a generator has nothing else to generate
ab -n 10000 -c 50 (synchronous)
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      140   159   69.1  145     976
Processing:   338 7408 5452.2 6231    46247
Waiting:      338 7407 5452.2 6230    46247
Total:        482 7567 5442.4 6377   46401

Percentage of the requests served within a certain time (ms)
  50%   6377
  66%   8540
  75%  10131
  80%  11068
  90%  13419
  95%  16077
  98%  23883
  99%  30173
 100%  46401 (longest request)
ab -n 10000 -c 50 (asynchronous)
Connection Times (ms)
              min mean[+/-sd]    median   max
Connect:      140   669 1375.6    151    21193
Processing:   189   338 300.0     256    15320
Waiting:      189   335 243.7     255     4143
Total:        332 1007 1407.6     438    21450

Percentage of the requests served within a certain time (ms)
  50%    438
  66%    565
  75%    732
  80%   1272
  90%   3372
  95%   3456
  98%   3762
  99%   9366
 100%  21450 (longest request)
What's the difference?
Wrong


for f in Fact.query():
   f.rating = random.normalvariate(400, 20)
   f.put()
Why?
Right: map_async

@tasklets.tasklet
def randomize_rating(f):
  f.rating = random.normalvariate(400, 20)
  raise tasklets.Return(f.put_async())

@context.toplevel
def randomize_all():
  Fact.query().map_async(randomize_rating)
Right: map_async
What else should I know?
•context and its event loop

•caches

•new datatypes

•new names for old types

•repeated = True

•StructuredProperty, LocalStructuredProperty

•compress

•shorter response times and more efficient instance usage
Where do I find it?


•official builds

•http://code.google.com/p/appengine-ndb-experiment/downloads/list

•"Bleeding" edge

•hg clone https://code.google.com/p/appengine-ndb-experiment/

•version 0.7 released yesterday
To know more


•documentation:

 http://code.google.com/p/appengine-ndb-experiment/

•Google group:

 http://groups.google.com/group/appengine-ndb-discuss/
Thanks



Thanks to the fine people who hang out on the appengine-ndb-discuss
group, in special to Guido and Vladimir, whose suggestions pointed me on
the right direction.

Contenu connexe

Tendances

Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
PTCL
 

Tendances (12)

Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
random forest regression
random forest regressionrandom forest regression
random forest regression
 
Array programs
Array programsArray programs
Array programs
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for free
 
Fast, stable and scalable true radix sorting with Matt Dowle at useR! Aalborg
Fast, stable and scalable true radix sorting with Matt Dowle at useR! AalborgFast, stable and scalable true radix sorting with Matt Dowle at useR! Aalborg
Fast, stable and scalable true radix sorting with Matt Dowle at useR! Aalborg
 
Use of django at jolt online v3
Use of django at jolt online v3Use of django at jolt online v3
Use of django at jolt online v3
 
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The CloudMongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
 
Real World Optimization
Real World OptimizationReal World Optimization
Real World Optimization
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 
Heaps
HeapsHeaps
Heaps
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
 
Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1
 

Similaire à Boredom comes to_those_who_wait

Capacity Management from Flickr
Capacity Management from FlickrCapacity Management from Flickr
Capacity Management from Flickr
xlight
 
Metrics 2.0 @ Monitorama PDX 2014
Metrics 2.0 @ Monitorama PDX 2014Metrics 2.0 @ Monitorama PDX 2014
Metrics 2.0 @ Monitorama PDX 2014
Dieter Plaetinck
 

Similaire à Boredom comes to_those_who_wait (20)

High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016
 
112 portfpres.pdf
112 portfpres.pdf112 portfpres.pdf
112 portfpres.pdf
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Machine Learning with Microsoft Azure
Machine Learning with Microsoft AzureMachine Learning with Microsoft Azure
Machine Learning with Microsoft Azure
 
Machine Learning with Apache Flink at Stockholm Machine Learning Group
Machine Learning with Apache Flink at Stockholm Machine Learning GroupMachine Learning with Apache Flink at Stockholm Machine Learning Group
Machine Learning with Apache Flink at Stockholm Machine Learning Group
 
Capacity Planning for Linux Systems
Capacity Planning for Linux SystemsCapacity Planning for Linux Systems
Capacity Planning for Linux Systems
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Capacity Management from Flickr
Capacity Management from FlickrCapacity Management from Flickr
Capacity Management from Flickr
 
Metrics 2.0 @ Monitorama PDX 2014
Metrics 2.0 @ Monitorama PDX 2014Metrics 2.0 @ Monitorama PDX 2014
Metrics 2.0 @ Monitorama PDX 2014
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Small pieces loosely joined
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joined
 
Performance
PerformancePerformance
Performance
 
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning PerformanceAnirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
 
Apache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and FriendsApache Flink Overview at SF Spark and Friends
Apache Flink Overview at SF Spark and Friends
 
Junhua wang ai_next_con
Junhua wang ai_next_conJunhua wang ai_next_con
Junhua wang ai_next_con
 
Java 8 Concurrency Updates
Java 8 Concurrency UpdatesJava 8 Concurrency Updates
Java 8 Concurrency Updates
 
High-Performance Hibernate - JDK.io 2018
High-Performance Hibernate - JDK.io 2018High-Performance Hibernate - JDK.io 2018
High-Performance Hibernate - JDK.io 2018
 
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CAApache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
 
Monitoring with Prometheus
Monitoring with PrometheusMonitoring with Prometheus
Monitoring with Prometheus
 
Deep Learning Inference at speed and scale
Deep Learning Inference at speed and scaleDeep Learning Inference at speed and scale
Deep Learning Inference at speed and scale
 

Plus de Ricardo Bánffy

Faça seu próprio servidor pirata com OpenVZ
Faça seu próprio servidor pirata com OpenVZFaça seu próprio servidor pirata com OpenVZ
Faça seu próprio servidor pirata com OpenVZ
Ricardo Bánffy
 

Plus de Ricardo Bánffy (15)

Continuous testing of a terminal font
Continuous testing of a terminal fontContinuous testing of a terminal font
Continuous testing of a terminal font
 
Monitoring and automation
Monitoring and automationMonitoring and automation
Monitoring and automation
 
Measure everything you can
Measure everything you canMeasure everything you can
Measure everything you can
 
Lessons learned after 190M lessons served
Lessons learned after 190M lessons servedLessons learned after 190M lessons served
Lessons learned after 190M lessons served
 
Anti-patterns
Anti-patternsAnti-patterns
Anti-patterns
 
TDD with Python and App Engine
TDD with Python and App EngineTDD with Python and App Engine
TDD with Python and App Engine
 
TDD com Python e App Engine
TDD com Python e App EngineTDD com Python e App Engine
TDD com Python e App Engine
 
Da persistência de idéias ruins
Da persistência de idéias ruinsDa persistência de idéias ruins
Da persistência de idéias ruins
 
Quem espera sempre cansa
Quem espera sempre cansaQuem espera sempre cansa
Quem espera sempre cansa
 
Zope
ZopeZope
Zope
 
Extreme Programming
Extreme ProgrammingExtreme Programming
Extreme Programming
 
Django para infográficos
Django para infográficosDjango para infográficos
Django para infográficos
 
Faça seu próprio servidor pirata com OpenVZ
Faça seu próprio servidor pirata com OpenVZFaça seu próprio servidor pirata com OpenVZ
Faça seu próprio servidor pirata com OpenVZ
 
CVS
CVSCVS
CVS
 
Ganhando dinheiro com software livre
Ganhando dinheiro com software livreGanhando dinheiro com software livre
Ganhando dinheiro com software livre
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Boredom comes to_those_who_wait

  • 1. Boredom comes to those who wait Asynchronous calls to Datastore Plus
  • 2. What you should know •toplevels/tasklets •futures •yield (you are going to build lots of generators) •you'll use yield instead of return (most of the time) •don't think about threads •..._async •the query API changes •an insanely great use for comparator overrides
  • 3. How it used to be done class Fact(model.Model):     text = model.TextProperty()     rating = model.FloatProperty(default = 400.)     random_index = model.ComputedProperty(         lambda self : random.randint(0,             sys.maxint)) (...) for i in range(10):     Fact(text = 'Fact %d' % i).put()
  • 4. Digression: _ah/stats •A good way to understand the performance of your apps •If you are doing something wrong, it'll become obvious Easy to enable on app.yaml: builtins: (...) - appstats: on
  • 5. How the first example behaves locally
  • 6. … and on the server
  • 7. The asynchronous way futures = [] for i in range(10):     futures.append(Fact(text = 'Fact %d' %         i).put_async()) [ f.get_result() for f in futures ]   Gives the opportunity to aggregate puts into one large datastore operation (and we don't have to worry about it)
  • 10. Better: toplevel/tasklet @context.toplevel (decorating something – usually a request handler – that will call the following tasklet)   @tasklets.tasklet def init_facts()   futures = []   for i in range(10):     futures.append(Fact(text = 'Fact %d' %       i).put_async())   yield futures   Yield allows the toplevel event loop to manage other generators making asynchronous calls
  • 11. … even better @context.toplevel (decorating your handler) @tasklets.tasklet def init_facts() Futures = [] for i in range(10): futures.append(Fact(text = 'Fact %d' % i).put_async()) raise tasklets.Return(futures) Because it's considered polite to raise things when a generator has nothing else to generate
  • 12. ab -n 10000 -c 50 (synchronous) Connection Times (ms) min  mean[+/-sd] median   max Connect: 140 159 69.1 145 976 Processing: 338 7408 5452.2 6231    46247 Waiting: 338 7407 5452.2 6230    46247 Total: 482 7567 5442.4 6377   46401 Percentage of the requests served within a certain time (ms)   50%   6377   66%   8540   75%  10131   80%  11068   90%  13419   95%  16077   98%  23883   99%  30173  100%  46401 (longest request)
  • 13. ab -n 10000 -c 50 (asynchronous) Connection Times (ms) min mean[+/-sd] median   max Connect: 140 669 1375.6 151 21193 Processing: 189 338 300.0 256 15320 Waiting: 189 335 243.7 255 4143 Total: 332 1007 1407.6 438 21450 Percentage of the requests served within a certain time (ms)   50%    438   66%    565   75%    732   80%   1272   90%   3372   95%   3456   98%   3762   99%   9366  100%  21450 (longest request)
  • 15. Wrong for f in Fact.query(): f.rating = random.normalvariate(400, 20) f.put()
  • 16. Why?
  • 17. Right: map_async @tasklets.tasklet def randomize_rating(f):   f.rating = random.normalvariate(400, 20)   raise tasklets.Return(f.put_async()) @context.toplevel def randomize_all():   Fact.query().map_async(randomize_rating)
  • 19. What else should I know? •context and its event loop •caches •new datatypes •new names for old types •repeated = True •StructuredProperty, LocalStructuredProperty •compress •shorter response times and more efficient instance usage
  • 20. Where do I find it? •official builds •http://code.google.com/p/appengine-ndb-experiment/downloads/list •"Bleeding" edge •hg clone https://code.google.com/p/appengine-ndb-experiment/ •version 0.7 released yesterday
  • 21. To know more •documentation: http://code.google.com/p/appengine-ndb-experiment/ •Google group: http://groups.google.com/group/appengine-ndb-discuss/
  • 22. Thanks Thanks to the fine people who hang out on the appengine-ndb-discuss group, in special to Guido and Vladimir, whose suggestions pointed me on the right direction.