YASE - Yet Another Software Engineer
Locust (locust.io
) is a tool written in Python that integrates perfectly with your FastAPI project.
gevent
(coroutines), great for generating high concurrency with fewer resources compared to thread/process-based solutions.pip install locust
Configure the class for the test (in this case, only 3 routes are tested):
from locust import HttpUser, task, between
import random
class FastAPIUser(HttpUser):
# Waits between 1 and 5 seconds between task executions for a user
wait_time = between(1, 5)
# host = "[http://127.0.0.1:8000](http://127.0.0.1:8000)" # Replace with your app's URL (can also be set via CLI)
@task
def get_root(self):
# Example: GET request to the root
self.client.get("/")
@task(3) # This task is executed 3 times more often than others
def get_items_by_id(self): # Renamed for clarity
# Example: GET request to a common endpoint
item_id = random.randint(1, 100)
# Use 'name' to group similar URLs in the report
self.client.get(f"/items/{item_id}", name="/items/[id]")
@task
def create_item(self):
# Example: POST request to create a resource
new_item = {"name": f"LocustItem_{random.randint(1000, 9999)}", "price": random.uniform(10.0, 500.0)}
self.client.post("/items/", json=new_item, name="/items/create") # Assuming /items/ endpoint for POST
def on_start(self):
# Code executed when a simulated user starts (e.g., login)
# print("Simulated user starting...")
# Example login:
# response = self.client.post("/login", json={"username":"test_user", "password":"password"})
# if response.ok:
# self.token = response.json().get("access_token")
# if self.token:
# self.client.headers = {'Authorization': f'Bearer {self.token}'}
# else:
# print(f"Login failed: {response.status_code}")
print("Simulated user starting...")
def on_stop(self):
# Code executed when a simulated user stops (e.g., logout)
print("Simulated user stopping.")
And then run the file just created:
locust -f your_locust_file.py --host=[http://127.0.0.1:8000](http://127.0.0.1:8000) # Replace your_locust_file.py
(Note: Added --host
to the command line as it’s a common way to specify it)
At this point, opening the page at the address:
http://localhost:8089
you can monitor the test results in real-time.
/
). Test the most used endpoints, those critical for the business, and those you suspect might be slow (e.g., complex queries, I/O-intensive operations). Simulate realistic user flows if possible (e.g., login -> read data -> modify data).top
, htop
, vmstat
).Analysis and Optimization:
await
ed, use run_in_executor
for heavy synchronous code.--workers
) is fundamental. A common starting point is (2 * NUM_CPU_CORES) + 1
, but it must be tested.