iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦗

Performing Database Load Testing with Locust

に公開

Introduction

Locust is primarily designed for load testing against HTTP requests, so performing load tests on a database requires a bit of ingenuity.
In this article, I will introduce how to use Locust to perform load testing on a database.

Here, I will show an example of load testing a database using MySQL, but by changing the module used to connect to the database, you can perform similar tests on other databases as well.

What is Locust?

Locust is an open-source load testing tool written in Python.
It allows you to perform load tests on web applications and APIs.

In Locust, you can write your test scenarios in Python.

https://locust.io/

Prerequisites

Environment

  • os: macOS Sonoma 14.2.1
  • Python 3.12.3

DB

  • MySQL Ver 9.1.0 (Docker container)
  • DB Name: sample_db
  • Table Name: employees
  • Records:
    id name age department
    1 Alice 30 Sales
    2 Bob 25 Marketing
    3 Charlie 35 HR

Steps

1. Creating a Virtual Environment (venv)

Here, we will create a virtual environment and install the necessary packages.
If you are not using a virtual environment, this step is not necessary.

Create a project directory

mkdir locust_db_test
cd locust_db_test

Create a virtual environment

python3 -m venv venv

Activate the virtual environment

source venv/bin/activate

For Windows, please execute the following command:

venv\Scripts\activate

2. Installing Required Packages

Install Locust

pip install locust

Install the MySQL driver

Install the appropriate driver for the database you want to load test.

pip install mysql-connector-python

3. Creating the Locust File

Create locustfile.py

Create locustfile.py in the locust_db_test directory.

from locust import User, TaskSet, task, between
import mysql.connector

# MySQL connection settings
def create_mysql_connection():
    # Returns a MySQL connection object
    return mysql.connector.connect(
        host="localhost",       # MySQL server host (set IP address for containers or remote hosts)
        user="root",            # MySQL username
        password="password",    # MySQL password
        database="sample_db",   # Database name to use
    )


class MySQLQueryTaskSet(TaskSet):

    @task
    def execute_query(self):
        # Connect to the database
        connection = create_mysql_connection()
        cursor = connection.cursor()

        # Execute query
        query = "SELECT * FROM employees;"
        cursor.execute(query)

        # Fetch results
        rows = cursor.fetchall()
        print(f"result: {rows}")

        # Close connection
        cursor.close()
        connection.close()


class MySQLUser(User):
    tasks = [MySQLQueryTaskSet] # Specify tasks
    wait_time = between(1, 5)   # Set wait time between requests (in seconds)
  • MySQLQueryTaskSet class
    A class for executing queries.
  • MySQLUser class
    Defines the user who executes the tasks by inheriting from Locust's User class.
  • tasks property
    Specifies the tasks that the user will execute.
  • wait_time property
    Sets a random wait time between requests within the specified range.
    Example: between(1, 5) will wait randomly between 1 and 5 seconds.

4. Starting Locust

Run the command in the directory containing locustfile.py

locust -f locustfile.py

Access http://localhost:8089 in your browser

locust

Enter the test settings and click the START button

  • Number of users (peak concurrency): Specify the number of concurrent users (at peak).
  • Ramp up (users started/second): The speed at which users are added (number of users per second).
  • Host: The hostname of the test target.
  • Advanced options: Other options.

While you can run the test even if the Host field is left empty, entering the target hostname will display it in the test results.

5. Checking Test Results

Check test results in the terminal

If you have written the code as described above, the query results will be displayed in the terminal.

result: [(1, 'Alice', 30, 'Sales'), (2, 'Bob', 25, 'Marketing'), (3, 'Charlie', 35, 'HR')]
result: [(1, 'Alice', 30, 'Sales'), (2, 'Bob', 25, 'Marketing'), (3, 'Charlie', 35, 'HR')]
result: [(1, 'Alice', 30, 'Sales'), (2, 'Bob', 25, 'Marketing'), (3, 'Charlie', 35, 'HR')]
result: [(1, 'Alice', 30, 'Sales'), (2, 'Bob', 25, 'Marketing'), (3, 'Charlie', 35, 'HR')]
…

Check test results in the browser

Returning to your browser and clicking the "CHARTS" tab, you can check the test results in graphs.

However, there is no change in graphs such as "Total Request per Second" or "Response Time."
This is because Locust is designed to perform tests against HTTP requests by default.

Therefore, the execution results of queries against the DB are not displayed.
To display the query execution results in the graphs, you need to modify the program slightly.

locust

6. Displaying Query Execution Results in Graphs

Modify locustfile.py as follows

locustfile.py
- from locust import User, TaskSet, task, between
+ from locust import User, TaskSet, task, between, events
  import mysql.connector
+ import time

  # MySQL connection settings
  def create_mysql_connection():
      return mysql.connector.connect(
        host="localhost",       # MySQL server host (set IP address for containers or remote hosts)
        user="root",            # MySQL username
        password="password",    # MySQL password
        database="sample_db",   # Database name to use
      )

  class MySQLQueryTaskSet(TaskSet):

      @task
      def execute_query(self):
          # Connect to the database
          connection = create_mysql_connection()
          cursor = connection.cursor()

+         # Measure time when executing the query
+         start_time = time.time()
+         try:
              query = "SELECT * FROM employees;"
              cursor.execute(query)

              # Fetch results
              rows = cursor.fetchall()
              print(f"result: {rows}")

+             # Report elapsed time if successful
+             total_time = (time.time() - start_time) * 1000  # Convert to milliseconds
+             events.request.fire(
+                 request_type="mysql",
+                 name="execute_query",
+                 response_time=total_time,
+                 response_length=len(rows),
+             )
+          except Exception as e:
+             # Report error if an error occurs
+             total_time = (time.time() - start_time) * 1000  # Convert to milliseconds
+             events.request.fire(
+                 request_type="mysql",
+                 name="execute_query",
+                 response_time=total_time,
+                 exception=e,
+             )
+         finally:
              # Close connection
              cursor.close()
              connection.close()

  class MySQLUser(User):
    tasks = [MySQLQueryTaskSet] # Specify tasks
    wait_time = between(1, 5)   # Set wait time between requests (in seconds)
  • events.request.fire()
    This is the method for displaying query execution results in graphs.

    • request_type
      Specifies the type of request. Normally, HTTP methods like GET or POST are specified, but for database queries, you should specify a clear name like mysql.
    • name
      Specifies the name of the request.
    • response_time
      Specifies the response time of the request.
    • response_length
      Specifies the length of the response.
    • exception
      Specifies the error if one occurs.

Start Locust again and run the test

The query execution results will be displayed in the graphs as shown below.

locust

Summary

In this article, I introduced how to perform load testing on a database using Locust.
Since Locust is designed with the assumption of load testing against HTTP requests, some ingenuity is required when performing load tests on a database.

When performing database load tests, you can check the test results in detail by including code for database connection settings and for displaying query execution results in graphs.

Discussion