Increase performance with a faster HTTP client

Locust’s default HTTP client uses python-requests. It provides a nice API that many python developers are familiar with, and is very well-maintained. But if you’re planning to run tests with very high throughput and have limited hardware for running Locust, it is sometimes not efficient enough.

Because of this, Locust also comes with FastHttpUser which uses geventhttpclient instead. It provides a very similar API and uses significantly less CPU time, sometimes increasing the maximum number of requests per second on a given hardware by as much as 5x-6x.

It is impossible to say how many requests Locust can do on your particular hardware, using your particular test plan, so you’ll need to test it out. Check Locust’s console output, it will log a warning if it is limited by CPU.

In a best case scenario (doing small requests inside a while True-loop) a single Locust process (limited to one CPU core) can do around 16000 requests per second using FastHttpUser, and 4000 using HttpUser (tested on a 2021 M1 MacBook Pro and Python 3.11)

The relative improvement may be even bigger with bigger request payloads, but it may also be smaller if your test is doing CPU intensive things not related to requests.

Of course, in reality you should run one locust process per CPU core.

Note

As long as your load generator CPU is not overloaded, FastHttpUser’s response times should be almost identical to those of HttpUser. It does not make individual requests faster.

How to use FastHttpUser

Just subclass FastHttpUser instead of HttpUser:

from locust import task, FastHttpUser

class MyUser(FastHttpUser):
    @task
    def index(self):
        response = self.client.get("/")

Concurrency

A single FastHttpUser/geventhttpclient session can run concurrent requests, you just have to launch greenlets for each request:

@task
def t(self):
    def concurrent_request(url):
        self.client.get(url)

    pool = gevent.pool.Pool()
    urls = ["/url1", "/url2", "/url3"]
    for url in urls:
        pool.spawn(concurrent_request, url)
    pool.join()

Note

FastHttpUser/geventhttpclient is very similar to HttpUser/python-requests, but sometimes there are subtle differences. This is particularly true if you work with the client library’s internals, e.g. when manually managing cookies.

REST

FastHttpUser provides a rest method for testing REST/JSON HTTP interfaces. It is a wrapper for self.client.request that:

  • Parses the JSON response to a dict called js in the response object. Marks the request as failed if the response was not valid JSON.

  • Defaults Content-Type and Accept headers to application/json

  • Sets catch_response=True (so always use a with-block)

  • Catches any unhandled exceptions thrown inside your with-block, marking the sample as failed (instead of exiting the task immediately without even firing the request event)

from locust import task, FastHttpUser

class MyUser(FastHttpUser):
    @task
    def t(self):
        with self.rest("POST", "/", json={"foo": 1}) as resp:
            if resp.js is None:
                pass # no need to do anything, already marked as failed
            elif "bar" not in resp.js:
                resp.failure(f"'bar' missing from response {resp.text}")
            elif resp.js["bar"] != 42:
                resp.failure(f"'bar' had an unexpected value: {resp.js['bar']}")

For a complete example, see rest.py. That also shows how you can use inheritance to provide behaviours specific to your REST API that are common to multiple requests/testplans.

Note

This feature is new and details of its interface/implementation may change in new versions of Locust.

API

FastHttpUser class

class FastHttpUser(environment)[source]

FastHttpUser provides the same API as HttpUser, but uses geventhttpclient instead of python-requests as its underlying client. It uses considerably less CPU on the load generator, and should work as a simple drop-in-replacement in most cases.

client_pool = None

HTTP client pool to use. If not given, a new pool is created per single user.

concurrency = 10

Parameter passed to FastHttpSession. Describes number of concurrent requests allowed by the FastHttpSession. Default 10. Note that setting this value has no effect when custom client_pool was given, and you need to spawn a your own gevent pool to use it (as Users only have one greenlet). See test_fasthttp.py / test_client_pool_concurrency for an example.

connection_timeout = 60.0

Parameter passed to FastHttpSession

insecure = True

Parameter passed to FastHttpSession. Default True, meaning no SSL verification.

max_redirects = 5

Parameter passed to FastHttpSession. Default 5, meaning 4 redirects.

max_retries = 1

Parameter passed to FastHttpSession. Default 1, meaning zero retries.

network_timeout = 60.0

Parameter passed to FastHttpSession

rest(method, url, headers=None, **kwargs)[source]

A wrapper for self.client.request that:

  • Parses the JSON response to a dict called js in the response object. Marks the request as failed if the response was not valid JSON.

  • Defaults Content-Type and Accept headers to application/json

  • Sets catch_response=True (so always use a with-block)

  • Catches any unhandled exceptions thrown inside your with-block, marking the sample as failed (instead of exiting the task immediately without even firing the request event)

rest_(method, url, name=None, **kwargs)[source]

Some REST api:s use a timestamp as part of their query string (mainly to break through caches). This is a convenience method for that, appending a _=<timestamp> parameter automatically

FastHttpSession class

class FastHttpSession(environment, base_url, user, insecure=True, client_pool=None, ssl_context_factory=None, **kwargs)[source]
get(url, **kwargs)[source]

Sends a GET request

head(url, **kwargs)[source]

Sends a HEAD request

options(url, **kwargs)[source]

Sends a OPTIONS request

patch(url, data=None, **kwargs)[source]

Sends a POST request

post(url, data=None, **kwargs)[source]

Sends a POST request

put(url, data=None, **kwargs)[source]

Sends a PUT request

request(method, url, name=None, data=None, catch_response=False, stream=False, headers=None, auth=None, json=None, allow_redirects=True, context={}, **kwargs)[source]

Send and HTTP request Returns locust.contrib.fasthttp.FastResponse object.

Parameters
  • method – method for the new Request object.

  • url – path that will be concatenated with the base host URL that has been specified. Can also be a full URL, in which case the full URL will be requested, and the base host is ignored.

  • name – (optional) An argument that can be specified to use as label in Locust’s statistics instead of the URL path. This can be used to group different URL’s that are requested into a single entry in Locust’s statistics.

  • catch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, even if the response code is ok (2xx). The opposite also works, one can use catch_response to catch a request and then mark it as successful even if the response code was not (i.e 500 or 404).

  • data – (optional) String/bytes to send in the body of the request.

  • json – (optional) Dictionary to send in the body of the request. Automatically sets Content-Type and Accept headers to “application/json”. Only used if data is not set.

  • headers – (optional) Dictionary of HTTP Headers to send with the request.

  • auth – (optional) Auth (username, password) tuple to enable Basic HTTP Auth.

  • stream – (optional) If set to true the response body will not be consumed immediately and can instead be consumed by accessing the stream attribute on the Response object. Another side effect of setting stream to True is that the time for downloading the response content will not be accounted for in the request time that is reported by Locust.

class FastResponse(ghc_response, request=None, sent_request=None)[source]
property content

Unzips if necessary and buffers the received body. Careful with large files!

headers

Dict like object containing the response headers

json()[source]

Parses the response as json and returns a dict

property text

Returns the text content of the response as a decoded string