A Rust HTTP server for Python applications
The Rust HTTP server for Python
Granian is a Rust HTTP server for Python applications built on top of Hyper and Tokio.
The main reasons behind Granian design are:
Adopting Granian would thus be a good choice when:
On the other hand, Granian won't be the ideal option if:
trio or geventYou can install Granian using pip:
$ pip install granianCreate an application in your main.py:
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})and serve it using Granian CLI:
$ granian --interface asgi main:appCreate an application your main.py:
async def app(scope, proto):
assert scope.proto == 'http'
proto.response_str(
status=200,
headers=[
('content-type', 'text/plain')
],
body="Hello, world!"
)and serve it using Granian CLI:
$ granian --interface rsgi main:appCreate an application your main.py:
def app(environ, start_response):
start_response('200 OK', [('content-type', 'text/plain')])
return [b"Hello, world!"]and serve it using Granian CLI:
$ granian --interface wsgi main:appMind that Granian also provides several extra dependencies you might be interested into, in particular:
You can combine the above extras to suit your needs, eg:
$ pip install granian[pname,uvloop]For further information, check the options below.
You can check all the options provided by Granian with the --help command:
…Whenever Granian accepts a duration, it can be specified either as sole number, in which case it is interpreted as a number of seconds, or using one of the following suffixes:
| suffix | meaning |
|---|---|
s |
seconds (same as no suffix) |
m |
minutes |
h |
hours |
d |
days |
Despite being a Rust project, Granian is a good Python citizen and uses the standard library's logging module to produce logs. This means you can freely configure your logging level and format using the standard idioms you probably familiar with.
As many other web servers, Granian uses two different loggers, specifically:
_granian logger for runtime messagesgranian.access logger for access logsThe access log format can be configured by specifying the atoms (see below) to include in a specific format. By default Granian will use [%(time)s] %(addr)s - "%(method)s %(path)s %(protocol)s" %(status)d %(dt_ms).3f as the format.
The following atoms are available for use:
| identifier | description |
|---|---|
| addr | Client remote address |
| time | Datetime of the request |
| dt_ms | Request duration in ms |
| status | HTTP response status |
| path | Request path (without query string) |
| query_string | Request query string |
| method | Request HTTP method |
| scheme | Request scheme |
| protocol | HTTP protocol version |
| header{header-name} | Request header value for the provided (case insensitive) header-name |
Granian offers different options to configure the number of workers and threads to be run, in particular:
In general, Granian will try its best to automatically pick proper values for the threading configuration, leaving to you the responsibility to choose the number of workers you need.
There is no golden rule here, as these numbers will vastly depend both on your application behavior and the deployment target, but we can list some suggestions:
In regards of blocking threads, the option is irrelevant on asynchronous protocols, as all the interop will happen with the AsyncIO event loop which will also be the one holding the GIL for the vast majority of the time, and thus the value is fixed to a single thread; on synchronous protocols like WSGI instead, it will be the maximum amount of threads interacting – and thus trying to acquire the GIL – with your application code. All those threads will be spawned on-demand depending on the amount of concurrency, and they'll be shutdown after the amount of inactivity time specified with the relevant setting.
In general, and unless you have a very specific use-case to do so (for example, if your application have an average millisecond response, a very limited amount of blocking threads usually delivers better throughput) you should avoid to tune this threadpool size and configure a backpressure value that suits your needs instead. In that regards, please check the next section.
Also, you should generally avoid to configure workers and threads based on numbers suggested for other servers, as Granian architecture is quite different from projects like Gunicorn or Uvicorn.
Note: using multiple workers and respawn options (lifetime, max memory) on Linux requires kernel versions >= 5.14 and the
net.ipv4.tcp_migrate_reqsyctl option enabled. Otherwise, during workers respawns, queued connections in the backlog might be dropped.
Since Granian runs a separated Rust runtime aside of your application that will handle I/O and "send work" to the Python interpreter, a mechanism to avoid pushing more work that what the Python interpreter can actually do is provided: backpressure.
Backpressure in Granian operates at the single worker's connections accept loop, practically interrupting the loop in case too many requests are waiting to be processed down the line. It is a per-worker concurrency limiter: connections exceeding the configured value will wait in the worker's own socket queue – the network stack backlog provided by the OS kernel (and configured with the apposite parameter).
While on asynchronous protocols, the default value for the backpressure should work fine for the vast majority of applications, as work will be handled and suspended by the AsyncIO event loop, on synchronous protocols there's no way to predict the amount of interrupts (and thus GIL releases) your application would do on a single request, and thus you should configure a value that makes sense in your environment. For example, if your WSGI application never does I/O within a request-reponse flow, then you can't really go beyond serial, and thus any backpressure value above 2 wouldn't probably make any difference, as all the requests will just be waiting to acquire the GIL in order to be processed. On the other hand, if your application makes external network requests within the standard request-response flow, a large backpressure can help, as during the time spent on those code paths you can still process other requests. Another example would be if your application communicate with a database, and you have a limited amount of connections that can be opened to that database: in this case setting the backpressure to that value would definitely be the best option.
In general, think of backpressure as the maximum amount of concurrency you want to handle (per worker) in your application, after which Granian will halt and wait before pushing more work.
Warning: since backpressure interacts with the accept loop, it will limit connections, not the single requests. Keep-alive connections will handle multiple requests within a single connection, but Granian won't count those requests in the actual pressure. This also means, if you typically have several long-running keep-alive connections to your service (for example, if you run behind a reverse proxy), a backpressure value can prevent Granian to accept new connections once the amount of keep-alive connections reaches that limit. Under this circumstances, you want to ensure the configured backpressure is higher than the expected amount of keep-alive connections, and if you're trying to limit the concurrency, it's probably better to configure the blocking threads number rather than the backpressure itself.
Granian offers two different runtime threading paradigms, due to the fact the runtime can be multi-threaded – in opposition to what happens in Python event-loop which can only run as a single thread.
Given you specify N threads with the relevant option, in st mode Granian will spawn N single-threaded Rust runtimes, while in mt mode Granian will spawn a single multi-threaded runtime with N threads.
Benchmarks suggests st mode to be more efficient with a small amount of processes, while mt mode seems to scale more efficiently where you have a large number of CPUs. Real performance will though depend on specific application code, and thus your mileage might vary.
By default (auto mode), Granian will pick the best option based on the rest of its configuration.
Granian exposes the following runtime metrics in Prometheus format. All the metrics are prefixed with granian_, and the one
No open issues yet, or sync has not completed.