k6 can schedule different load patterns for different VU functions. A test with multiple workloads might better simulate traffic in the real world, where user behavior is rarely uniform. For example, most traffic to an e-commerce site might come from users who only search for items and read reviews. A small percentage of users might actively shop, performing actions that involve writes to the database and calls to different APIs.
The following sections provide examples of how to structure k6 scripts to split logic across VUs. To inspect the results for a certain behavior, you can create a custom metric or use Tags to filter by scenario, code block, or individual request.
Aim for simplicity
These techniques can create very complex configurations. However, more complexity creates more ambiguity in result interpretation
Split logic across scenarios
In this context, workload refers to the traffic pattern simulated by a scenario.
One way to distribute traffic is to use scenarios to schedule different workloads for different functions.
- Define multiple scenarios in your options.
- Use the scenario exec property to execute different VU functions with a workload.
For example, imagine a social media site that typically receives 100 concurrent users. Of those, 80 might visit their contacts page, and 20 might view the news. To configure such a distribution, make two scenarios with different throughput or VUs:
To view granular results for a specific scenario, you can filter by the built-in scenario tag.
Distribute logic by VU ID
In some cases, writing a scenario for each behavior might be inconvenient or impractical. As an alternative, you can distribute logic across a range of VUs with the execution context variables from the k6/execution module. With the exec object, you can scope logic to a specific instance, scenario, or across all VUs.
For example, this statement assigns behavior to the first 25 VUs in a test.
For more flexibility, you can use modulo expressions to distribute VUs according to percentages. For example, the following script distributes logic according to different user profiles:
- 40 percent of users check the news.
- 60 percent play a coinflip game.
- Half bet heads, and half bet tails.
To add a degree of random behavior, consider one of the randomizing functions from the k6 utils.
For example, this script randomly assigns one behavior to happen one-third of the time, and another to happen all other times.
For a more sophisticated example of randomizing, read this forum post.