QA AND TEST AUTOMATION · PART 9 · NON-FUNCTIONAL TESTING · PERFORMANCE · 83 OF 112

JMeter and Locust: Thread Groups, Correlation

Two more load tools you will meet: Apache JMeter, with test plans, thread groups, samplers, config elements, correlation with extractors, assertions, listeners and non-GUI runs, and Locust, where users are Python classes. A Locust run on ShopRung where each user signs up its own account, and a gate that failed the run when ShopRung's slow-search bug pushed search from 2 ms to 2.5 s.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Thread groups
  • timers
  • correlation with extractors
  • non-GUI runs
  • Locust users in Python
  • gate on p95, not just 200 OK

Notes

JMeter parts

JMeter is a Java desktop tool, and a test is a tree of elements saved as an XML file with a dot j m x extension. The test plan holds thread groups; each thread is one virtual user. Inside are HTTP request defaults for the host, a header manager, HTTP request samplers that send requests, extractors and assertions, timers for think time, and listeners that collect results. You build it in the GUI, but you run it without one.

Test plan tree
Test Plan
  Thread Group (users, ramp-up,
    loops or duration)
    HTTP Request Defaults (host)
    HTTP Header Manager
    HTTP Request samplers
    extractors, assertions
    timers (think time)
  Listeners (results)
saved as XML: plan.jmx

Thread groups

A thread group sets the number of threads, which are users, a ramp up period that starts them gradually, and a loop count or duration. Fifty threads with a sixty second ramp up start one new user every one point two seconds. Add a timer, such as a uniform random timer between one and three seconds, for think time. For arrival rate models like k6's, teams use JMeter plugins such as the arrivals thread group.

Thread Group settings
  • Number of threads: 50 (users)
  • Ramp-up period: 60 s (one new user every 1.2 s)
  • Loop count or duration: 10 min
  • action on error: continue
  • think time: Uniform Random Timer 1,000-3,000 ms
  • arrival rate: plugins such as Concurrency/Arrivals Thread

Correlation

Correlation means capturing a dynamic value from one response and sending it in later requests. Recorded scripts break without it, because tokens, session ids and order ids change every run. In JMeter, a JSON extractor under the login request reads dollar dot token into a variable called token, and the header manager sends Authorization Bearer, then token in curly braces. Regular expression and boundary extractors do the same for HTML and text.

Correlation in JMeter
POST /api/auth/login
  └ JSON Extractor
      Names: token
      JSON Path: $.token
HTTP Header Manager
  Authorization: Bearer ${token}
POST /api/cart/items ...

also: Regular Expression
  Extractor, Boundary Extractor

Running JMeter

Never run a load test from the GUI; it uses too much memory and distorts results. Run with dash n for no GUI, dash t for the plan, dash capital J to pass properties such as the host, read in the plan with the underscore underscore P function, dash l for the raw results file, and dash e dash o to generate an HTML dashboard. Response, JSON and duration assertions mark samples as failed.

Non-GUI run
jmeter -n -t plan.jmx \
  -Jhost=staging.example.com \
  -l results.jtl \
  -e -o report/

-n  no GUI (always, for load)
-J  property, read with
      ${__P(host)}
-l  raw results  -e -o HTML report
assertions: Response, JSON,
  Duration (max time)

Locust users

In Locust, a user is a Python class. On start runs once per virtual user: here it signs up a brand new ShopRung account, logs in, and stores the token as a default header, so twenty users have twenty separate carts. Tasks are weighted: three searches for each add to cart. We ran twenty users for twenty seconds: two hundred and twenty six requests, no failures, search median two milliseconds.

locustfile.py (shortened)
class Shopper(HttpUser):
  wait_time = between(1, 3)
  def on_start(self):
    # sign up + log in a NEW user
    self.client.headers[
      "Authorization"] = f"Bearer {t}"
  @task(3)
  def search(self): ...
  @task(1)
  def add_to_cart(self):
    self.client.post("/api/cart/items",..)

What it showed

The run showed something useful: login took about thirty six milliseconds and sign up about sixty, while search took two. ShopRung hashes passwords with PBKDF2 and sixty thousand rounds, which is slow on purpose, to make stolen password hashes hard to crack. That is why load scripts log in once per virtual user, not before every request; otherwise you are mostly load testing the password hash.

Medians from the run
search          2 ms
add to cart     3 ms
login          36 ms
signup         60 ms

why: ShopRung hashes passwords
  with PBKDF2, 60,000 rounds
  (slow by design, for safety)
→ log in once per user, not
  once per request

Catch a slow bug

Then we turned on ShopRung's slow search bug. Search went from two milliseconds to two and a half seconds, yet Locust reported zero failures, because every answer was 200 OK. Locust has no thresholds built in, so we added a quitting listener that checks the ninety fifth percentile and failure ratio. With the bug on, it printed gate failed and exited with code one; with the bug off, the same run exited zero.

slow-search on, 20 users
search median   2 ms → 2,500 ms
failures        0   (all 200 OK!)

@events.quitting.add_listener
def gate(environment, **kw):
  s = environment.stats.total
  p95 = s.get_response_time_
        percentile(0.95)
  if s.fail_ratio > 0.01 or p95 > 500:
    environment.process_exit_code = 1
→ "GATE FAILED: p95=2500", exit 1

Which tool?

Which tool? JMeter has a GUI, supports many protocols, including databases and message queues, and has a huge plugin set, but plans are XML that is hard to review. k6 uses JavaScript with thresholds built in and suits CI. Locust is plain Python with a web interface and distributed workers. Gatling is another popular choice with a code based DSL. The concepts are the same everywhere: users, think time, correlation, checks and goals.

Compared
  • JMeter: GUI, many protocols (HTTP, JDBC, JMS, FTP), huge plugin set, XML plans
  • k6: JavaScript, thresholds built in, CI-friendly
  • Locust: Python, flexible logic, web UI, distributed workers
  • Gatling: Scala/Java/JS DSL
  • same concepts everywhere

Common mistakes

Mistakes. Running load from the JMeter GUI. Recorded scripts with no correlation, so every request after login fails or, worse, quietly acts as a logged out user. Leaving the view results tree listener on during a load test, which eats memory. Logging in before every request. And counting every two hundred as success with no response time goal, which our slow search run showed passes a two and a half second search.

Avoid these
  • load tests run in the JMeter GUI
  • recorded scripts without correlation
  • "View Results Tree" listener left on during load
  • logging in before every call
  • 200 OK counted as success with no response time goal

Say it like this

In the interview: correlation is capturing a dynamic value, like a token or an order id, from a response with a JSON, regular expression or boundary extractor, storing it in a variable, and sending it in later requests. I build plans in the GUI but run them in non GUI mode, and I gate on the ninety fifth percentile and error rate, whether the tool is JMeter, k6, or Locust with a quitting listener.

In the interview
  • "Capturing a dynamic value, like a token or order id, from a response with a JSON, regex or boundary extractor into a variable, and sending it in later requests. I build plans in the GUI, run them with -n, and gate on p95 and error rate, in JMeter, k6 or a Locust quitting
  • listener."

Interview questions

Q1What is correlation in load testing?

Capturing dynamic values such as tokens or ids from a response (JSON, regex or boundary extractor) and reusing them in later requests.

Q2What is a thread group in JMeter?

The element that defines virtual users: number of threads, ramp-up period, and loop count or duration.

Q3Why run JMeter in non-GUI mode?

The GUI uses a lot of memory and CPU and distorts results; jmeter -n -t plan.jmx -l results.jtl -e -o report/ is the standard.

Q4How do you add think time in JMeter?

With timers such as the Uniform Random Timer or Constant Timer inside the thread group.

Q5How is a Locust test written?

A Python class extending HttpUser with wait_time, on_start for setup such as login, and @task methods with weights.

Q6How do you fail a Locust run on response time?

Add an events.quitting listener that checks stats (p95, fail_ratio) and sets environment.process_exit_code = 1.

Q7Why log in once per virtual user?

Password hashing is deliberately slow; logging in on every request mostly tests the hash and distorts results.

Q8Why is "zero failures" not enough?

Slow responses can still return 200 OK; with ShopRung's slow-search bug, search took 2.5 s with no failures, so goals must include response time.