Load Testing with Locust – Python Scenarios for Your Site

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Picture this: your site works fine with 100 visitors, but crashes at 1000. 50% of users leave if a page loads longer than 3 seconds. For e-commerce, downtime can cost up to $10,000 per hour. We are a team of engineers with 10 years of load testing experience. We develop load tests using Locust to identify bottlenecks before they impact your business. Our scenarios mimic real user behavior: login, product views, order placement. We run tests in CI/CD—you learn about problems during development, not after deployment. Over 100 successful projects for e-commerce, SaaS, and media. We guarantee your site will handle any load after our tests.

According to Locust documentation, "Locust is an open-source load testing tool written in Python." This explains its flexibility: scenarios are written in Python, allowing any logic—from simple GET requests to complex authentication flows with tokens.

How We Build Load Tests with Locust

Comparison: Locust vs. JMeter

Locust uses Python for flexibility in complex logic (e.g., token-based auth, dynamic data generation). JMeter uses XML, which is less readable. Locust scales easily: add 10 machines to simulate 100,000 users. In our tests, Locust generates load 3x faster on the same hardware.

Tool Script Language Scalability Web Interface
Locust Python High Yes
JMeter XML Medium Yes
k6 JavaScript High No

Why Choose Locust?

Key advantages: open source, active community, distributed mode support, and built-in web interface for real-time monitoring. We have used Locust for over 8 years and consider it the best choice for flexible load testing.

What Scenarios Do We Write?

Typical scenarios include:

  • Authentication and session management
  • Catalog search and filtering
  • Product detail page views
  • Add to cart and checkout
  • API calls to external services

Each scenario includes checks on status, response time, and data structure. We use weights to simulate different operation frequencies.

Example Basic Scenario

# locustfile.py
from locust import HttpUser, task, between
import random

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)

    def on_start(self):
        self.client.post("/api/auth/login", json={
            "email": f"user{random.randint(1,1000)}@test.com",
            "password": "testpassword"
        })

    @task(3)
    def browse_products(self):
        self.client.get(f"/api/products?page={random.randint(1,10)}")

    @task(2)
    def view_product(self):
        self.client.get(f"/api/products/{random.randint(1,500)}")

    @task(1)
    def create_order(self):
        self.client.post("/api/orders", json={
            "product_id": random.randint(1,100),
            "quantity": random.randint(1,3)
        })

This code is the test foundation. We add metrics and thresholds.

Metrics and Checks

from locust import events
from locust.runners import MasterRunner

@events.request.add_listener
def on_request(request_type, name, response_time, response_length, response,
               context, exception, start_time, url, **kwargs):
    if exception:
        print(f"Request failed: {name} - {exception}")
    elif response_time > 2000:
        print(f"Slow request: {name} - {response_time}ms")

@events.quitting.add_listener
def assert_stats(environment, **kwargs):
    stats = environment.runner.stats
    total = stats.total
    if total.fail_ratio > 0.01:
        print(f"FAIL: Error rate {total.fail_ratio:.2%} > 1%")
        environment.process_exit_code = 1
    if total.avg_response_time > 500:
        print(f"FAIL: Avg response time {total.avg_response_time:.0f}ms > 500ms")
        environment.process_exit_code = 1
    p99 = total.get_response_time_percentile(0.99)
    if p99 > 2000:
        print(f"FAIL: p99 {p99:.0f}ms > 2000ms")
        environment.process_exit_code = 1

We collect metrics for each request and set thresholds: error rate ≤1%, average response time ≤500ms, 99th percentile ≤2s. Exceeding stops the test with an error code.

Running Tests

# Headless mode for CI/CD
locust -f locustfile.py --headless --users 100 --spawn-rate 10 --run-time 5m --host YOUR_STAGING_URL --html report.html

# Distributed mode (multiple machines)
# Master
locust -f locustfile.py --master --expect-workers=3
# Workers
locust -f locustfile.py --worker --master-host=192.168.1.100

The web interface is available at http://localhost:8089 for manual control.

How to Integrate Load Tests into CI/CD

GitHub Actions Example

- name: Run Locust Load Test
  run: |
    locust -f locustfile.py --headless --users 50 --spawn-rate 5 --run-time 3m --host ${{ vars.STAGING_URL }} --html load-report.html
  continue-on-error: false
- name: Upload Report
  uses: actions/upload-artifact@v3
  with:
    name: load-test-report
    path: load-report.html

Tests run automatically on each deploy. If thresholds are exceeded, the pipeline fails—you know about the issue before going live.

Process and Results

Stages of Work

  1. Analysis – study architecture, identify critical operations, collect real user logs.
  2. Design – write scenarios with weights, add checks.
  3. Implementation – create locustfile.py, configure distributed mode and CI/CD.
  4. Execution – run tests on staging and production.
  5. Report – provide load test graphs, percentiles, optimization recommendations.

What's Included in the Result

Component Description
Scenarios 3–5 locustfile.py files with different user types
Configuration Settings for headless, distributed, CI/CD (GitHub Actions/GitLab CI)
Documentation Scenario descriptions, launch instructions, report interpretation
Support 30 days of optimization consulting after delivery

Timeline and Pricing

Load test development takes 2 to 5 days depending on complexity. Pricing is individual—contact us for an estimate. Investment pays off by preventing downtime: a single failure during peak season can exceed $100,000 in losses.

Common Load Testing Mistakes

  • Uniform scenarios – all users do the same, not reflecting real behavior.
  • No checks – test "passes" even with 50% errors.
  • Testing only on staging – production may behave differently due to configuration or load.
  • Insufficient machines – one server can't provide enough load for 10,000 users.
  • Ignoring caches – tests must be run on a "cold" cache.
Detailed distributed mode setup example In distributed mode, the master distributes load among workers. Use cloud machines to scale up to 100,000 users.

Conclusion

Load tests with Locust help avoid downtime and customer loss. We'll assess your project in 1 day—contact us for a free consultation. The lost revenue from a non-working site can reach $50,000 per day—don't risk it.

Why are unit tests important but not a panacea?

A bug found by a unit test costs minutes to fix. The same bug in production costs hours of incident response, compensations, and lost trust. In an online store project, a discount calculation error passed manual testing, went to production, and processed 37 orders at zero price in 4 hours. An automated test for edge cases would have caught it on the first push. With 7+ years in web application testing and over 200 projects delivered, we’ve seen this pattern repeat across industries.

Jest is the standard for JavaScript/TypeScript, but unit tests are justified only where there is isolated logic: transformation functions, validators, business rules, utilities. Testing React components with Jest + Testing Library is correct for behavioral tests: "button appears after loading", "form shows error on empty email". Snapshot tests (toMatchSnapshot) are a trap: they break on any layout change and become noise that developers update without looking. Code coverage is a poor quality metric: 80% coverage can be achieved with tests that check nothing. Coverage shows that code executed, not that it works correctly.

Criteria Jest Vitest
Speed for large projects Medium (Babel transformation) 10–20x faster (ES modules)
Integration with Vite Via plugin Native
Monorepos Requires configuration Out of the box

Vitest as an alternative to Jest for Vite projects: 10–20x faster due to native ES modules without Babel transformation. For monorepos with thousands of tests, the speed difference is noticeable. Wikipedia on unit testing describes the theoretical foundation — we apply it with real CI pipelines.

How to set up E2E tests that are not flaky?

Playwright outperforms Cypress on key parameters: native multi-tab, multi-origin, iframe support; parallel execution at test level; WebKit, Firefox, Chromium out of the box; no iframe for the app — tests run in a real browser.

Playwright codegen records actions and generates a test — a good starting point, but generated code needs refactoring. Locators by text content are fragile: getByRole('button', { name: 'Place order' }) is more robust than locator('.btn-primary').

Page Object Model is the standard for organizing E2E tests. Each page is a separate class with methods instead of direct locators. When a button moves from header to sidebar — change in one place, not across all tests.

Flaky tests typically arise from race conditions between request and render, animations without wait, and dependency on external APIs. Solution: page.waitForResponse() instead of page.waitForTimeout(), mocking external APIs via page.route().

// Bad
await page.click('#submit');
await page.waitForTimeout(2000);
await expect(page.locator('.success')).toBeVisible();

// Good
await page.click('#submit');
await page.waitForResponse(resp =>
  resp.url().includes('/api/orders') && resp.status() === 201
);
await expect(page.getByRole('alert', { name: /order created/i })).toBeVisible();

Our engineers guarantee test stability in CI. Playwright’s official documentation covers all API details — we use it daily on projects with millions of users.

How do Core Web Vitals affect ranking?

Google uses Core Web Vitals in ranking. Lighthouse CLI in CI pipeline: on every deploy we check that LCP < 2.5s, CLS < 0.1, INP < 200ms. Google Chrome study: 53% of users leave a site if it takes longer than 3 seconds to load — our tests prevent such losses.

Real problems that Lighthouse finds:

  • Hero image without width/height attributes: CLS 0.35 on load.
  • JavaScript bundle 2.1MB synchronously blocking parsing: INP 450ms.
  • Fonts without font-display: swap: invisible text until font loads (FOIT).
  • Unoptimized hero image 4MB: LCP 8.2s.

Lighthouse CI (lhci) saves metric history and posts a comment to PR with degradation. For one e‑commerce client, optimizing these metrics improved conversion by 18% and reduced server costs by $12k annually.

What does load testing solve?

k6 is a load testing tool with a JavaScript API. Scenarios are written as code, versioned in git, run in CI. Three main scenarios:

  • Spike test — sharp load increase: 0 → 1000 users in 30 seconds. Simulates a campaign launch. Shows system's ability to handle spikes.
  • Soak test — stable load for 2–4 hours. Detects memory leaks, connection pool exhaustion, performance degradation.
  • Stress test — load above expected (150–200% of peak). Shows breaking point and graceful degradation.

Thresholds:

thresholds: {
  http_req_duration: ['p95<500', 'p99<1000'],
  http_req_failed: ['rate<0.01'],
}

p95 < 500ms means 95% of requests respond faster than half a second. If threshold is not met, k6 exits with error code, CI pipeline fails.

In one online store project, we detected API degradation at the 4th hour of the test: p95 increased from 200ms to 2s due to connection leaks. After optimization, the client saved $15k per year on incident response and extra infrastructure.

Testing pyramid in a project

Level Tool Quantity Speed
Unit Vitest/Jest Many (thousands) <5 min
Integration Vitest + supertest Medium 5–15 min
E2E Playwright Few (happy path) 10–30 min
Load k6 On schedule 30–60 min
Performance Lighthouse CI On every deploy 5 min

What does the work include?

  • Audit of current coverage and identification of critical user flows.
  • Writing unit tests for key business logic, integration tests for API, E2E for user scenarios.
  • Setting up parallel execution in CI (sharded workers for Playwright).
  • Load testing with report and recommendations.
  • Test case documentation, training your team on test practices.
  • 1-month warranty support after implementation.
  • Delivery of all test artefacts (code, CI configs, run histories).

How do we work?

  1. Analysis — audit of current testing, identification of weak spots, priority setting.
  2. Design — tool selection, test plan writing, approval.
  3. Implementation — writing tests, CI integration.
  4. Testing — running all levels, result analysis, bug fixing.
  5. Deployment — going live, metric monitoring, team training.

Timeline

Setting up a full test pipeline (Jest + Playwright + k6 + Lighthouse CI) from scratch: 2–4 weeks. E2E test coverage of an existing project (20–30 scenarios): 3–6 weeks. Load testing with report and recommendations: 1–2 weeks. Cost calculated individually after audit.

Ready to discuss your project? Leave a request — we will audit your current web application testing for free and propose a plan that can save up to 60% on incident costs. Get a consultation on web application testing — contact us today.