SlideShare a Scribd company logo
●
    scaling case. From 4 users to 90k+
                   ●


              ●
                Jaime Buelta
         ●
           Soft. Developer at
                   ●
The Game
Get image from game
Utopia Kingdoms
●   Fantasy strategy game
●   Build your own Kingdom
●   Create armies and attack other Kingdoms
●   Join other Kingdoms in an Alliance
●   Manage resources
●   Available in Facebook and Kongregate
    http://www.facebook.com/UtopiaKigdomsGame
http://www.kongregate.com/games/JoltOnline/utopia-kingdoms
Technology stack
Technology Stack - Backend

       Python
 Cherrypy framework

  Amazon SimpleDB
 Linux in Amazon EC2
Stack of technologies - Frontend

            HTML
( generated by Genshi templates)


            jQuery
Stack of technologies - Frontend

            HTML
( generated by Genshi templates)


            jQuery
Some points of interest
                 (will discuss them later)

●
    Your resources (population, gold, food, etc)
    grows with time
●
    You actions (build something, attack a player)
    typically takes some time
●
    Players are ranked against the rest
●
    You can add friends and enemies
Do not guess
Measure
Measurement tools
●   OS tools
    ●   Task manager (top)
    ●
        IO Monitor (iostat)
●   Monitoring tools (Munin, Nagios)

●   Logs
    ●
        Needs to find a good compromise detailed/relevance
●   Profiling
You've got to love profiling
●
    Generate profiles with cProfile module
    Profile whole application with
    python -m cProfile -o file.prof my_app.py
    (not very useful in a web app)


●
    If you're using a framework, profile only your
    functions to reduce noise
Profile decorator (example)
def profile_this(func):
  import cProfile
  prof = cProfile.Profile()
  retval = prof.runcall(func)
  filename = 'profile-{ts}.prof'.format(time.time())
  prof.dumpstats(filename)
  return retval
Analyzing profile
●
    gprof2dot
    ●
        Using dot, convert to graph
        gprof2dot -f pstats file.prof | dot -Tpng -o file.png
    ●
        Good for workflows

●
    RunSnakeRun
    ●
        Good for cumulative times
Example of RunSnakeRun
           RAZR
Example of gprof2dot
The power of cache
All static should be out of python
●
    Use a good web server to serve all static
    content (Static HTML, CSS, JavaScript code)
●
    Some options
    ●
        Apache
    ●
        Nginx
    ●
        Cherokee
    ●
        Amazon S3
Use memcached
(and share the cache between your servers)
Example
●
    Asking for friends/enemies to DB
    ●
        Costly request in SimpleDB (using SQL statement)
●
    On each request
●
    Cache the friends on memcache for 1 hour
●
    Invalidate the cache if adding/removing
    friends or enemies
Caching caveats
●
    Cache only after knowing there is a problem
●
    Do not trust in cache for storage
●
    Take a look on size of cached data
●
    Choosing a good cache time can be difcult /
    Invalidate cache can be complex
●
    Some data is too dynamic to be cached
Caching is not just memcached
●
    More options available:
    ●
      Get on memory on start
    ●
      File cache
    ●
      Cache client side
Parse templates just once
●
    The template rendering modules have options
    to parse the templates just once
●
    Be sure to activate it in production
●
    In development, you'll most likely want to
    parse them each time

●
    Same apply to regex, specially complex ones
More problems
Rankings
●
    Sort players on the DB is slow when you grow
    the number of players
●
    Solution:
    ●
        Independent ranking server (operates just in
        memory)
    ●
        Works using binary trees
    ●
        Small Django project, communicates using xmlrpc
●
    Inconvenient:
    ●
        Data is not persistent, if the rankings server goes
        down, needs time to reconstruct the rankings
Database pulling - Resources
●
    There was a process just taking care of the
    growth of resources.
    ●
        It goes element by element, and increasing the
        values
    ●
        It pulls the DB constantly, even when the user has
        their values to maximum
●
    Increment the resources of a user just the next
    time is accessed (by himself or by others)
    ●
        No usage of DB when the user is not in use
    ●
        The request already reads from DB the user
Database pulling - Actions
●
    Lots of actions are delayed. Recruit a unit,
    buildings, raids...
●
    A process check each user if an action has to
    be done NOW.
    ●
        Tons of reads just to check “not now”
    ●
        Great delay in some actions, as they are not
        executed in time
Database pulling - Actions
●
    Implement a queue to execute the actions at
    the proper time:
    ●
        Beanstalk (allows deferred extraction)
    ●
        A process listen to this queue and performs the
        action, independently from request servers.
    ●
        The process can be launched in a diferent
        machine.
    ●
        Multiple process can extract actions faster.
DataBase Issues
Amazon SimpleDB
●
    Key – Value storage
●
    Capable of SQL queries
●
    Store a dictionary (schemaless, multiple
    columns)
●
    All the values are strings
●
    Access through boto module
●
    Pay per use
Problems with SimpleDB
●
    Lack of control
    ●
        Can't use local copy
        –   In development, you must access Amazon servers (slow
            and costly)
    ●
        Can't backup except manually
    ●
        Can't analyze or change DB (e.g. can't define
        indexes)
    ●
        Can't monitor DB
Problems with SimpleDB
●
    Bad tool support
●
    Slow and high variability (especially on SQL
    queries)
    ●
        Sometime, the queries just timeout and had to be
        repeated.
Migrate to MongoDB
MongoDB
●
    NoSQL
●
    Schemaless
●
    Fast
●
    Allow complex queries
●
    Retain control (backups, measure queries, etc)
●
    Previous experience using it from ChampMan
Requisites of the migration
●
    Low-level approach
●
    Objects are basically dictionaries
●
    Be able to save dirty fields (avoid saving
    unchanged values)
●
    Log queries to measure performance
MongoSpell
●
    Thin wrap over pymongo
●
    Objects are just dictionary-like elements
●
    Minimal schema
●
    Fast!
●
    Able to log queries
●
    It will probably be released soon as Open
    Source
Definition of collections
class Spell(Document):
 collection_name = 'spells'
 needed_fields = ['name',
          'cost',
          'duration']
 optional_fields = [
           'elemental',
           ]
 activate_dirty_fields = True
 indexes = ['name__unique', 'cost']
Querying from DB
Spell.get_from_db(name='fireball')
Spell.filter()
Spell.filter(sort='name')
Spell.filter(name__in=['fireball', 'magic missile'])
Spell.filter(elemental__fire__gt=2)
Spell.filter(duration__gt=2,
             cost=3,
             hint='cost')
Spell.filter(name='fireball', only='cost')
Some features
●
    Dirty fields
●
    No type checks
●
    Query logs
●
    10x faster than SimpleDB!!!
Query logs



[07:46:06]-   2.6   ms   –   get_from_db   -   Reinforcement - Reinforcements.py(31)
[07:46:06]-   4.3   ms   -   get_from_db   -   Player   - Player.py(876)
[07:46:10]-   0.1   ms   -   filter        -   Membership- AllianceMembership.py(110)
[07:46:10]-   1.3   ms   -   get_from_db   -   Reinforcement -Reinforcements.py(31)
[07:46:10]-   1.4   ms   -   get_from_db   -   Notifications - Notifications.py (56)
Scalability vs Efciency
Scalable vs Efcient
    Scalable                Efficient
●
    Can support more    ●
                            Can support more
    users adding more       users with the same
    elements                elements

    Work on both to achieve your goals
Keep measuring and improving!
(and monitor production to be proactive)
Thank you for your interest!

           Questions?


           jaime.buelta@gmail.com
 http://WrongSideOfMemphis.wordpress.com
           http://www.joltonline.com

More Related Content

What's hot

Tool it Up! - Session #3 - MySQL
Tool it Up! - Session #3 - MySQLTool it Up! - Session #3 - MySQL
Tool it Up! - Session #3 - MySQLtoolitup
 
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)Ontico
 
Get More Out of MySQL with TokuDB
Get More Out of MySQL with TokuDBGet More Out of MySQL with TokuDB
Get More Out of MySQL with TokuDBTim Callaghan
 
Optimizing MongoDB: Lessons Learned at Localytics
Optimizing MongoDB: Lessons Learned at LocalyticsOptimizing MongoDB: Lessons Learned at Localytics
Optimizing MongoDB: Lessons Learned at Localyticsandrew311
 
Using NoSQL MongoDB with ColdFusion
Using NoSQL MongoDB with ColdFusionUsing NoSQL MongoDB with ColdFusion
Using NoSQL MongoDB with ColdFusionindiver
 
Store Beyond Glorp
Store Beyond GlorpStore Beyond Glorp
Store Beyond GlorpESUG
 
MySQL-Mixer-Livenation
MySQL-Mixer-LivenationMySQL-Mixer-Livenation
MySQL-Mixer-LivenationHari Tatrakal
 
WiredTiger MongoDB Integration
WiredTiger MongoDB Integration WiredTiger MongoDB Integration
WiredTiger MongoDB Integration MongoDB
 
MongoDB Best Practices in AWS
MongoDB Best Practices in AWS MongoDB Best Practices in AWS
MongoDB Best Practices in AWS Chris Harris
 
In-Memory Computing: How, Why? and common Patterns
In-Memory Computing: How, Why? and common PatternsIn-Memory Computing: How, Why? and common Patterns
In-Memory Computing: How, Why? and common PatternsSrinath Perera
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVMIvaylo Pashov
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLanandology
 

What's hot (15)

PostgreSQL and MySQL
PostgreSQL and MySQLPostgreSQL and MySQL
PostgreSQL and MySQL
 
Tool it Up! - Session #3 - MySQL
Tool it Up! - Session #3 - MySQLTool it Up! - Session #3 - MySQL
Tool it Up! - Session #3 - MySQL
 
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
 
Get More Out of MySQL with TokuDB
Get More Out of MySQL with TokuDBGet More Out of MySQL with TokuDB
Get More Out of MySQL with TokuDB
 
Optimizing MongoDB: Lessons Learned at Localytics
Optimizing MongoDB: Lessons Learned at LocalyticsOptimizing MongoDB: Lessons Learned at Localytics
Optimizing MongoDB: Lessons Learned at Localytics
 
Using NoSQL MongoDB with ColdFusion
Using NoSQL MongoDB with ColdFusionUsing NoSQL MongoDB with ColdFusion
Using NoSQL MongoDB with ColdFusion
 
Store Beyond Glorp
Store Beyond GlorpStore Beyond Glorp
Store Beyond Glorp
 
MySQL-Mixer-Livenation
MySQL-Mixer-LivenationMySQL-Mixer-Livenation
MySQL-Mixer-Livenation
 
Java 2
Java 2Java 2
Java 2
 
WiredTiger MongoDB Integration
WiredTiger MongoDB Integration WiredTiger MongoDB Integration
WiredTiger MongoDB Integration
 
MongoDB Best Practices in AWS
MongoDB Best Practices in AWS MongoDB Best Practices in AWS
MongoDB Best Practices in AWS
 
In-Memory Computing: How, Why? and common Patterns
In-Memory Computing: How, Why? and common PatternsIn-Memory Computing: How, Why? and common Patterns
In-Memory Computing: How, Why? and common Patterns
 
Rit 2011 ats
Rit 2011 atsRit 2011 ats
Rit 2011 ats
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVM
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
 

Viewers also liked

KM & Libraries Taming the KM Monster
KM & Libraries Taming the KM MonsterKM & Libraries Taming the KM Monster
KM & Libraries Taming the KM Monstercreynolds2009
 
FGS 2011: How I Built A $10,000/month Flash Game In My Spare Time
FGS 2011: How I Built A $10,000/month Flash Game In My Spare TimeFGS 2011: How I Built A $10,000/month Flash Game In My Spare Time
FGS 2011: How I Built A $10,000/month Flash Game In My Spare Timemochimedia
 
What is Universal Design for Learning?
What is Universal Design for Learning?What is Universal Design for Learning?
What is Universal Design for Learning?Cindy Jennings
 
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati Python Ireland
 
Hairdresser slideshow
Hairdresser slideshowHairdresser slideshow
Hairdresser slideshowKenzieLamson
 
What is Universal Design
What is Universal DesignWhat is Universal Design
What is Universal DesignCindy Jennings
 

Viewers also liked (6)

KM & Libraries Taming the KM Monster
KM & Libraries Taming the KM MonsterKM & Libraries Taming the KM Monster
KM & Libraries Taming the KM Monster
 
FGS 2011: How I Built A $10,000/month Flash Game In My Spare Time
FGS 2011: How I Built A $10,000/month Flash Game In My Spare TimeFGS 2011: How I Built A $10,000/month Flash Game In My Spare Time
FGS 2011: How I Built A $10,000/month Flash Game In My Spare Time
 
What is Universal Design for Learning?
What is Universal Design for Learning?What is Universal Design for Learning?
What is Universal Design for Learning?
 
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
 
Hairdresser slideshow
Hairdresser slideshowHairdresser slideshow
Hairdresser slideshow
 
What is Universal Design
What is Universal DesignWhat is Universal Design
What is Universal Design
 

Similar to Utopia Kingdoms scaling case. From 4 users to 50.000+

Journey through high performance django application
Journey through high performance django applicationJourney through high performance django application
Journey through high performance django applicationbangaloredjangousergroup
 
kranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High loadkranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High loadKrivoy Rog IT Community
 
Performance optimization techniques for Java code
Performance optimization techniques for Java codePerformance optimization techniques for Java code
Performance optimization techniques for Java codeAttila Balazs
 
Intro to XPages for Administrators (DanNotes, November 28, 2012)
Intro to XPages for Administrators (DanNotes, November 28, 2012)Intro to XPages for Administrators (DanNotes, November 28, 2012)
Intro to XPages for Administrators (DanNotes, November 28, 2012)Per Henrik Lausten
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with GatlingPetr Vlček
 
An evening with Postgresql
An evening with PostgresqlAn evening with Postgresql
An evening with PostgresqlJoshua Drake
 
Tech meetup: Web Applications Performance
Tech meetup: Web Applications PerformanceTech meetup: Web Applications Performance
Tech meetup: Web Applications PerformanceSantex Group
 
MongoDB Pros and Cons
MongoDB Pros and ConsMongoDB Pros and Cons
MongoDB Pros and Consjohnrjenson
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend PerformanceThomas Weinert
 
OSMC 2019 | How to improve database Observability by Charles Judith
OSMC 2019 | How to improve database Observability by Charles JudithOSMC 2019 | How to improve database Observability by Charles Judith
OSMC 2019 | How to improve database Observability by Charles JudithNETWAYS
 
AWS big-data-demystified #1.1 | Big Data Architecture Lessons Learned | English
AWS big-data-demystified #1.1  | Big Data Architecture Lessons Learned | EnglishAWS big-data-demystified #1.1  | Big Data Architecture Lessons Learned | English
AWS big-data-demystified #1.1 | Big Data Architecture Lessons Learned | EnglishOmid Vahdaty
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...javier ramirez
 
Node.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleNode.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleDmytro Semenov
 
MongoDB: Advantages of an Open Source NoSQL Database
MongoDB: Advantages of an Open Source NoSQL DatabaseMongoDB: Advantages of an Open Source NoSQL Database
MongoDB: Advantages of an Open Source NoSQL DatabaseFITC
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo dbLawrence Mwai
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGearsAlessandro Molina
 
PGConf APAC 2018 - High performance json postgre-sql vs. mongodb
PGConf APAC 2018 - High performance json  postgre-sql vs. mongodbPGConf APAC 2018 - High performance json  postgre-sql vs. mongodb
PGConf APAC 2018 - High performance json postgre-sql vs. mongodbPGConf APAC
 
QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...javier ramirez
 

Similar to Utopia Kingdoms scaling case. From 4 users to 50.000+ (20)

Journey through high performance django application
Journey through high performance django applicationJourney through high performance django application
Journey through high performance django application
 
kranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High loadkranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High load
 
Performance optimization techniques for Java code
Performance optimization techniques for Java codePerformance optimization techniques for Java code
Performance optimization techniques for Java code
 
Intro to XPages for Administrators (DanNotes, November 28, 2012)
Intro to XPages for Administrators (DanNotes, November 28, 2012)Intro to XPages for Administrators (DanNotes, November 28, 2012)
Intro to XPages for Administrators (DanNotes, November 28, 2012)
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with Gatling
 
An evening with Postgresql
An evening with PostgresqlAn evening with Postgresql
An evening with Postgresql
 
The Accidental DBA
The Accidental DBAThe Accidental DBA
The Accidental DBA
 
Tech meetup: Web Applications Performance
Tech meetup: Web Applications PerformanceTech meetup: Web Applications Performance
Tech meetup: Web Applications Performance
 
MongoDB Pros and Cons
MongoDB Pros and ConsMongoDB Pros and Cons
MongoDB Pros and Cons
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 
OSMC 2019 | How to improve database Observability by Charles Judith
OSMC 2019 | How to improve database Observability by Charles JudithOSMC 2019 | How to improve database Observability by Charles Judith
OSMC 2019 | How to improve database Observability by Charles Judith
 
AWS big-data-demystified #1.1 | Big Data Architecture Lessons Learned | English
AWS big-data-demystified #1.1  | Big Data Architecture Lessons Learned | EnglishAWS big-data-demystified #1.1  | Big Data Architecture Lessons Learned | English
AWS big-data-demystified #1.1 | Big Data Architecture Lessons Learned | English
 
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
Cómo se diseña una base de datos que pueda ingerir más de cuatro millones de ...
 
Node.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleNode.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scale
 
MongoDB: Advantages of an Open Source NoSQL Database
MongoDB: Advantages of an Open Source NoSQL DatabaseMongoDB: Advantages of an Open Source NoSQL Database
MongoDB: Advantages of an Open Source NoSQL Database
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGears
 
MongoDB Online Training.pdf
MongoDB Online Training.pdfMongoDB Online Training.pdf
MongoDB Online Training.pdf
 
PGConf APAC 2018 - High performance json postgre-sql vs. mongodb
PGConf APAC 2018 - High performance json  postgre-sql vs. mongodbPGConf APAC 2018 - High performance json  postgre-sql vs. mongodb
PGConf APAC 2018 - High performance json postgre-sql vs. mongodb
 
QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...QuestDB: ingesting a million time series per second on a single instance. Big...
QuestDB: ingesting a million time series per second on a single instance. Big...
 

More from Python Ireland

Python Ireland - Who, how, what
Python Ireland - Who, how, whatPython Ireland - Who, how, what
Python Ireland - Who, how, whatPython Ireland
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
What's the Scoop with Python 3?
What's the Scoop with Python 3?What's the Scoop with Python 3?
What's the Scoop with Python 3?Python Ireland
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
Introduction to Erlang for Python Programmers
Introduction to Erlang for Python ProgrammersIntroduction to Erlang for Python Programmers
Introduction to Erlang for Python ProgrammersPython Ireland
 
Web-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using PythonWeb-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using PythonPython Ireland
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentPython Ireland
 
Python vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experiencePython vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experiencePython Ireland
 
Python Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - AppenginePython Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - AppenginePython Ireland
 
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...Python Ireland
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland
 
Python Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with DjangoPython Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with DjangoPython Ireland
 
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to PythonPython Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to PythonPython Ireland
 
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and BoltsPython Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and BoltsPython Ireland
 
Python for cloud computing
Python for cloud computingPython for cloud computing
Python for cloud computingPython Ireland
 
IPython: The awesome python shell
IPython: The awesome python shellIPython: The awesome python shell
IPython: The awesome python shellPython Ireland
 
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory GeogheganPython Ireland
 

More from Python Ireland (20)

Async I/O in Python
Async I/O in PythonAsync I/O in Python
Async I/O in Python
 
Python Ireland - Who, how, what
Python Ireland - Who, how, whatPython Ireland - Who, how, what
Python Ireland - Who, how, what
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
What's the Scoop with Python 3?
What's the Scoop with Python 3?What's the Scoop with Python 3?
What's the Scoop with Python 3?
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
Introduction to Erlang for Python Programmers
Introduction to Erlang for Python ProgrammersIntroduction to Erlang for Python Programmers
Introduction to Erlang for Python Programmers
 
Web-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using PythonWeb-service based Mobile Geospatial Application Development using Python
Web-service based Mobile Geospatial Application Development using Python
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
 
Python vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experiencePython vs JLizard.... a python logging experience
Python vs JLizard.... a python logging experience
 
Vim and Python
Vim and PythonVim and Python
Vim and Python
 
Python Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - AppenginePython Ireland Nov 2009 Talk - Appengine
Python Ireland Nov 2009 Talk - Appengine
 
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Python Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with DjangoPython Ireland Nov 2010 - RESTing with Django
Python Ireland Nov 2010 - RESTing with Django
 
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to PythonPython Ireland Feb '11 Talks: Introduction to Python
Python Ireland Feb '11 Talks: Introduction to Python
 
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and BoltsPython Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
 
Lambada
LambadaLambada
Lambada
 
Python for cloud computing
Python for cloud computingPython for cloud computing
Python for cloud computing
 
IPython: The awesome python shell
IPython: The awesome python shellIPython: The awesome python shell
IPython: The awesome python shell
 
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
[Python Ireland] Cocoa and the Python/C API by Rory Geoghegan
 

Recently uploaded

PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfalexjohnson7307
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 

Recently uploaded (20)

PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 

Utopia Kingdoms scaling case. From 4 users to 50.000+

  • 1. scaling case. From 4 users to 90k+ ● ● Jaime Buelta ● Soft. Developer at ●
  • 4. Utopia Kingdoms ● Fantasy strategy game ● Build your own Kingdom ● Create armies and attack other Kingdoms ● Join other Kingdoms in an Alliance ● Manage resources ● Available in Facebook and Kongregate http://www.facebook.com/UtopiaKigdomsGame http://www.kongregate.com/games/JoltOnline/utopia-kingdoms
  • 6. Technology Stack - Backend Python Cherrypy framework Amazon SimpleDB Linux in Amazon EC2
  • 7. Stack of technologies - Frontend HTML ( generated by Genshi templates) jQuery
  • 8. Stack of technologies - Frontend HTML ( generated by Genshi templates) jQuery
  • 9. Some points of interest (will discuss them later) ● Your resources (population, gold, food, etc) grows with time ● You actions (build something, attack a player) typically takes some time ● Players are ranked against the rest ● You can add friends and enemies
  • 11. Measurement tools ● OS tools ● Task manager (top) ● IO Monitor (iostat) ● Monitoring tools (Munin, Nagios) ● Logs ● Needs to find a good compromise detailed/relevance ● Profiling
  • 12. You've got to love profiling ● Generate profiles with cProfile module Profile whole application with python -m cProfile -o file.prof my_app.py (not very useful in a web app) ● If you're using a framework, profile only your functions to reduce noise
  • 13. Profile decorator (example) def profile_this(func): import cProfile prof = cProfile.Profile() retval = prof.runcall(func) filename = 'profile-{ts}.prof'.format(time.time()) prof.dumpstats(filename) return retval
  • 14. Analyzing profile ● gprof2dot ● Using dot, convert to graph gprof2dot -f pstats file.prof | dot -Tpng -o file.png ● Good for workflows ● RunSnakeRun ● Good for cumulative times
  • 17. The power of cache
  • 18. All static should be out of python ● Use a good web server to serve all static content (Static HTML, CSS, JavaScript code) ● Some options ● Apache ● Nginx ● Cherokee ● Amazon S3
  • 19. Use memcached (and share the cache between your servers)
  • 20. Example ● Asking for friends/enemies to DB ● Costly request in SimpleDB (using SQL statement) ● On each request ● Cache the friends on memcache for 1 hour ● Invalidate the cache if adding/removing friends or enemies
  • 21. Caching caveats ● Cache only after knowing there is a problem ● Do not trust in cache for storage ● Take a look on size of cached data ● Choosing a good cache time can be difcult / Invalidate cache can be complex ● Some data is too dynamic to be cached
  • 22. Caching is not just memcached ● More options available: ● Get on memory on start ● File cache ● Cache client side
  • 23. Parse templates just once ● The template rendering modules have options to parse the templates just once ● Be sure to activate it in production ● In development, you'll most likely want to parse them each time ● Same apply to regex, specially complex ones
  • 25. Rankings ● Sort players on the DB is slow when you grow the number of players ● Solution: ● Independent ranking server (operates just in memory) ● Works using binary trees ● Small Django project, communicates using xmlrpc ● Inconvenient: ● Data is not persistent, if the rankings server goes down, needs time to reconstruct the rankings
  • 26. Database pulling - Resources ● There was a process just taking care of the growth of resources. ● It goes element by element, and increasing the values ● It pulls the DB constantly, even when the user has their values to maximum ● Increment the resources of a user just the next time is accessed (by himself or by others) ● No usage of DB when the user is not in use ● The request already reads from DB the user
  • 27. Database pulling - Actions ● Lots of actions are delayed. Recruit a unit, buildings, raids... ● A process check each user if an action has to be done NOW. ● Tons of reads just to check “not now” ● Great delay in some actions, as they are not executed in time
  • 28. Database pulling - Actions ● Implement a queue to execute the actions at the proper time: ● Beanstalk (allows deferred extraction) ● A process listen to this queue and performs the action, independently from request servers. ● The process can be launched in a diferent machine. ● Multiple process can extract actions faster.
  • 30. Amazon SimpleDB ● Key – Value storage ● Capable of SQL queries ● Store a dictionary (schemaless, multiple columns) ● All the values are strings ● Access through boto module ● Pay per use
  • 31. Problems with SimpleDB ● Lack of control ● Can't use local copy – In development, you must access Amazon servers (slow and costly) ● Can't backup except manually ● Can't analyze or change DB (e.g. can't define indexes) ● Can't monitor DB
  • 32. Problems with SimpleDB ● Bad tool support ● Slow and high variability (especially on SQL queries) ● Sometime, the queries just timeout and had to be repeated.
  • 34. MongoDB ● NoSQL ● Schemaless ● Fast ● Allow complex queries ● Retain control (backups, measure queries, etc) ● Previous experience using it from ChampMan
  • 35. Requisites of the migration ● Low-level approach ● Objects are basically dictionaries ● Be able to save dirty fields (avoid saving unchanged values) ● Log queries to measure performance
  • 36. MongoSpell ● Thin wrap over pymongo ● Objects are just dictionary-like elements ● Minimal schema ● Fast! ● Able to log queries ● It will probably be released soon as Open Source
  • 37. Definition of collections class Spell(Document): collection_name = 'spells' needed_fields = ['name', 'cost', 'duration'] optional_fields = [ 'elemental', ] activate_dirty_fields = True indexes = ['name__unique', 'cost']
  • 38. Querying from DB Spell.get_from_db(name='fireball') Spell.filter() Spell.filter(sort='name') Spell.filter(name__in=['fireball', 'magic missile']) Spell.filter(elemental__fire__gt=2) Spell.filter(duration__gt=2, cost=3, hint='cost') Spell.filter(name='fireball', only='cost')
  • 39. Some features ● Dirty fields ● No type checks ● Query logs ● 10x faster than SimpleDB!!!
  • 40. Query logs [07:46:06]- 2.6 ms – get_from_db - Reinforcement - Reinforcements.py(31) [07:46:06]- 4.3 ms - get_from_db - Player - Player.py(876) [07:46:10]- 0.1 ms - filter - Membership- AllianceMembership.py(110) [07:46:10]- 1.3 ms - get_from_db - Reinforcement -Reinforcements.py(31) [07:46:10]- 1.4 ms - get_from_db - Notifications - Notifications.py (56)
  • 42. Scalable vs Efcient Scalable Efficient ● Can support more ● Can support more users adding more users with the same elements elements Work on both to achieve your goals
  • 43. Keep measuring and improving! (and monitor production to be proactive)
  • 44. Thank you for your interest! Questions? jaime.buelta@gmail.com http://WrongSideOfMemphis.wordpress.com http://www.joltonline.com