Skip to main content

Python: Asynchronous Networking APIs and MySQL

In my talk on Python concurrency, I talked about the multiple different approaches to asynchronous network programming in the Python world. I showed Twisted and Tornado Web, and then I compared them to stackless Python and gevent. Toward the end of the talk, I covered how MySQL plays into all this.

In the Python world, we usually use a MySQL driver that is a Python binding to a low-level driver written in C. The low-level driver written in C isn't written to use Python's socket module in any way. In fact, it has nothing to do with Python. Hence, it's impossible to take Twisted or Tornado Web and have them make the low-level driver behave asynchronously.

That's a problem. If you go to all the trouble of making your code asynchronous, it sucks to have one request that is held up on a long query block all the requests in your process. People handle this in different ways.

The Twisted guys can put the MySQL driver on its own thread. You might have 100 requests being handled by Twisted, and 10 threads devoted to MySQL connections.

The Tornado Web guys (from what I can tell) handle it differently. They allow MySQL queries to block the entire process. However, they compensate in two ways. They lean heavily on their asynchronous web client wherever possible. They also make use of multiple Python processes. Hence, if you're handling 500 simultaneous request, you might use nginx to split them among 10 different Tornado Web processes. Each process is handling 50 simultaneous requests. If one of those requests needs to make a call to the database, only 50 (instead of 500) requests are blocked.

At lolapps, they use Tornado Web too (at least for certain things). Their approach is to lean heavily on memcached and avoid talking to MySQL in real time whenever possible.

At IronPort, Sam Rushing (who's now working on a cool project called Irken) wrote a custom MySQL driver in Python. It was built with his proprietary version of stackless Python in mind, and hence it was asynchronous.

I think the same thing should be possible in the gevent world. MySQL Connector/Python is a MySQL driver written in pure Python. Since gevent permits you to use asynchronous networking APIs without forcing you to use continuation-passing style, it's possible that gevent could be used with MySQL Connector/Python to make your MySQL queries asynchronous too. Thank goodness for greenlet!

This is a topic I feel strongly about. I remember in the early days of Java, the JVM supported kernel threads as well as green threads. Some people would use green threads and then do multi-threaded programming with blocking socket APIs. What a lot of them didn't realize is that with green threads, if you call a synchronous networking API, you're blocking all your threads, not just one of them. Similarly, I feel strongly that if you're going to all the trouble of using an asynchronous web framework, your MySQL queries should be asynchronous too.


jjinux said…
turingpup said...

Hey JJ,

Last night I managed to accomplish what I set out to do: I strapped gevent onto the side of my tornado project and replaced the underlying db drivers with pg8000 (which is 100% python code) and upgraded sqlalchemy to the latest version to support it. I now have a fully feature web stack on top of gevent :) It ran some unit tests and it seems to be solid, but I still need to confirm that I'm getting the speed/concurrency from gevent and there aren't any blocking calls.
Anonymous said…
Have you considered DBSlayer? It's an HTTP/JSON interface to MySQL - you can set it up and then use the async HTTP client in an event-based framework to make your DB queries.
Adrian said…
Also: libpq for postgresql has an asynchronous interface, exposed by psycopg2. I don't think I've seen it actually used in anything though.
bsdemon said…
I have the same idea about using gevent with MySQL in async way. Moreover, I want to put in production system based on gevent + myconnpy + sqlalchemy. But I think I should rewrite some code from myconnpy in C/Cython — I speak about data marshaling... but I need to profile first.
Unknown said…
Concurrence ( contains a fully asynchronous driver for mysql.
jjinux said…
Henk, that's huge! Thanks! I'm so glad to see these ideas out in the wild ;)
Anonymous said…
Concurrence also integrates easily with SQLAlchemy because it can provide the normal python dbapi interface (e.g. all the async stuff is not visible for consumers of the api). There is a (currently undocumented class SqlAlchemyPoolAdapter in concurrence.database.ext that can be used as a drop in replacement for the normal sql alchemy pool stuff).
jjinux said…
Very nice :)
libor michalek said…
FYI: the python mysql connection we use in the slide/egroups coroutine environment is now on github. Likewise there's a project in there to implement some wire decode in C for performance. (The mysql wire protocol has almost no encode to speak of, SQL is sent directly to the server)
jjinux said…
Libor, that's fantastic!
Jonas Tarnstrom said…
We've written a MySQL driver for Python with our without gevent in pure C/C++.

Performance is about 3-7 times faster than our Python written alternatives.


Would love feedback and benchmarks!
jjinux said…

Popular posts from this blog

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from