
monkey.patch_all(). One call at the top of a module, and every blocking socket in the standard library quietly becomes cooperative. That line sat under a surprising amount of real-time advertising in the early 2010s. TellApart, the retargeting company Twitter bought in 2015, ran the bidding front ends of its predictive marketing platform as a gevent Python stack, and its engineers were candid about both why it worked and where it bit them. A decade later the library is still maintained and gevent in production is still common, which makes the questions they faced worth answering again.
Greenlets give Python cheap concurrency
The core trick is the greenlet: a coroutine implemented as a C extension, with its own small stack, that can pause and resume without the operating system knowing. gevent greenlets are cheap enough that a single process can hold tens of thousands of them, one per open connection, where threads would run out of memory or drown in context switches.
Underneath sits an event loop. Early releases used libevent, which is what TellApart’s engineers named when they described their setup. gevent 1.0 switched to libev, and later versions added libuv as an alternative loop (it is the default on Windows). The loop watches file descriptors; when a greenlet would block on a socket, it parks itself with the loop and the hub switches to another greenlet that is ready to run.
That is cooperative scheduling. Greenlets cooperate, threads compete. Nothing preempts a greenlet; it runs until it waits on I/O or explicitly yields. For an ad bidder that spends most of its time waiting on profile lookups and network writes, this is close to ideal concurrency: thousands of requests in flight, a single core, and no locks around shared state, because only one greenlet runs at a time.
TellApart used the library across its stack. The company’s engineers named the TellApart Front End servers, which answered bid requests from ad exchanges, and the open-source Taba aggregation service as core components built on it, and they gave a talk at Pinterest on its advantages and pitfalls. The Taba write-up describes a stateless Python server behind an Nginx reverse proxy, using greenlets for simple and fast cooperative concurrency.
Monkey-patching is the deal you sign
You get that concurrency without rewriting code because of monkey-patching. patch_all() replaces socket, ssl, time.sleep, select, threading and several other modules with gevent-aware versions. A plain requests.get() then yields to the loop while it waits for bytes.
The rule is strict: patch first. If anything imports ssl or creates a socket before the patch runs, that object keeps the blocking implementation, and gevent will warn about it at runtime. Put the patch in the entry point, before any other import.
Here is a bounded fan-out, the most common gevent Python pattern in production:
from gevent import monkey
monkey.patch_all() # first, before anything imports socket or ssl
from gevent.pool import Pool
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
session.mount("https://", HTTPAdapter(pool_connections=4, pool_maxsize=20))
pool = Pool(20) # never more than 20 greenlets in flight
def fetch(url):
try:
return url, session.get(url, timeout=2).status_code
except requests.RequestException as exc:
return url, type(exc).__name__
urls = ["https://example.com/"] * 100
for url, result in pool.imap_unordered(fetch, urls):
print(url, result)
Note the two numbers that match. The pool caps concurrency at 20; the HTTP adapter keeps up to 20 connections per host. If the second number is lower, urllib3 opens extra connections, discards them after use and logs a warning, and your latency goes up for no obvious reason.
Where gevent in production goes wrong
Every serious problem with gevent in production comes back to one fact: a greenlet that does not yield blocks every other greenlet in the process.
CPU-bound code stalls the loop
A bidder that scores a request with a heavy model, or a handler that parses a large JSON body, holds the loop for the whole computation. Other requests queue behind it, and an ad exchange with a deadline of about a tenth of a second simply drops the late answers. The real fix is to move CPU work into a separate process. The stopgap is to yield explicitly:
import gevent
def score_batch(rows, score):
total = 0.0
for i, row in enumerate(rows):
total += score(row)
if i % 500 == 0:
gevent.sleep(0) # let waiting greenlets run
return total
The library ships a monitor thread (enable it with the GEVENT_MONITOR_THREAD_ENABLE setting) that reports greenlets holding the loop longer than a threshold. Turn it on in staging before you guess.
C extensions that are not green
Monkey-patching only reaches Python code that uses the standard library. A C extension that opens its own sockets bypasses it entirely. The classic case is the C MySQL driver; psycopg2 needs a wait callback (the psycogreen package provides one) to cooperate. Pure-Python drivers such as PyMySQL work without help.
DNS resolution
Name lookups are easy to forget. The default resolver runs getaddrinfo in a thread pool, which is safe but can saturate under bursts of new hostnames. The GEVENT_RESOLVER setting switches to the c-ares or dnspython resolvers, each with its own quirks around /etc/hosts and search domains. Cache DNS results for hot hosts and most of this goes away.
Timeouts belong on every wait
A greenlet waiting forever on a socket costs almost nothing, which is why the leak goes unnoticed. In production, set a timeout on every network call, and wrap whole operations in gevent.Timeout when a request has a deadline of its own. A bidder that cannot answer in time should give up and free its connection, not hold it while the exchange has already moved on. The same goes for locks and queues from gevent.lock and gevent.queue: a get() without a timeout is a hang waiting to happen.
Pools keep the loop honest
Unbounded spawning is the other way services fall over. One greenlet per incoming request is fine until a downstream store slows down; then gevent greenlets pile up, memory climbs and every one of them holds a connection. A gevent.pool.Pool with a fixed size turns that into backpressure.
Connection pools need the same sizing discipline. A Redis or database pool smaller than the greenlet pool makes greenlets wait on each other; a much larger one overwhelms the server. TellApart’s Taba service kept all state in a small cluster of Redis instances and kept its workers stateless, so capacity was a matter of adding workers. The team’s post on pushing Python to high throughput reports scaling Taba from 10 million events per minute to 10 million per second, and names a pattern of combining generators with gevent greenlets into just-in-time processing pipelines.
The same post has a side-track worth remembering: CPython’s memory allocator fragments badly in long-running processes that churn through mixed large and small objects. TellApart’s engineers fought it with generators to reduce in-flight objects and by avoiding long-lived objects that ratchet the heap upward. That problem has nothing to do with gevent, and it bites asyncio services just the same.
gevent versus asyncio in 2026
asyncio arrived in Python 3.4 in 2014, async and await in 3.5, and it is now the standard-library answer to I/O concurrency. Its big advantage is visibility: every point where a coroutine can pause is marked with await. gevent hides those points, which is exactly why it is convenient and exactly why its bugs are hard to find.
For a new service, pick asyncio. Running gevent in production next to an asyncio event loop in the same process is possible with third-party bridges, but it doubles the number of schedulers you have to reason about; choose one model per service. The drivers are there (asyncpg, aiohttp, httpx, redis-py’s asyncio client), the frameworks are there, and the scheduling is explicit.
Pick gevent when the code already exists. That was TellApart’s situation in spirit: a Python codebase written in a blocking style, needing far more connections per core, at a time when asyncio did not yet exist. A large Django or Flask application with synchronous drivers can gain thousands of concurrent connections through Gunicorn’s gevent worker (gunicorn -k gevent --worker-connections 1000 app:app) without touching application code. Celery’s gevent pool and the Locust load-testing tool rely on the same trade. A gevent Python codebase that works should usually stay one; a rewrite to asyncio touches every function that does I/O. The rest of the company’s Python tooling, from its commandr CLI builder to its mrjob launcher, is collected in the engineering section.
The open question is free-threaded CPython. Python 3.13 shipped an experimental build without the global interpreter lock, and if it matures, plain threads become competitive for I/O-heavy services again. Whether greenlets and coroutines keep their edge once threads stop fighting over a single lock is something nobody has measured at scale yet.
Questions readers ask
Is gevent still maintained in 2026?
Yes. gevent still ships regular releases with wheels for current CPython versions on Linux, macOS and Windows, and widely used projects such as Gunicorn, Celery and Locust keep supporting it. It is not deprecated and not abandoned. What has changed is its position: new Python services usually start with asyncio, and gevent is mostly chosen for existing synchronous codebases.
How do gevent greenlets differ from threads?
A thread is scheduled by the operating system and can be interrupted at any point. A greenlet is a lightweight coroutine that runs until it voluntarily gives up control, which in gevent happens whenever it waits on I/O or calls a gevent sleep. Greenlets cost a few kilobytes each, so tens of thousands can live in one process, but one greenlet that never yields stops all the others.
Do I need to call monkey.patch_all() when using Gunicorn's gevent worker?
No. Gunicorn's gevent worker class patches the standard library itself when the worker starts. The usual trouble comes from code that imports and opens sockets in the master process before the workers fork, for example a database client created at module import time with preloading enabled. Create such clients inside the worker, after the patch has run.
Should a new gevent Python service be written today?
Rarely. For a new service, asyncio or a framework built on it gives you explicit await points, standard-library support and a larger ecosystem of async drivers. gevent still makes sense when you have a large body of blocking code, such as a Django or Flask application with synchronous database drivers, and need far more concurrent connections without rewriting every call.
Why does my gevent in production deployment freeze under load?
Almost always because something is blocking the event loop: a CPU-heavy function, a C extension doing its own network I/O, or a library imported before monkey-patching. gevent's monitor thread can report greenlets that hold the loop too long, which usually points straight at the culprit. Pool exhaustion, where every greenlet waits on a too-small connection pool, looks similar and is just as common.