Load Testing Using Gatling and Java # 4 : Session API


What is the Gatling Session?

In Gatling, the session represents the user context in each simulation. It's an immutable object that stores data relevant to a specific virtual user (VU), such as request responses, extracted variables, and other dynamic values needed during scenario execution. Each virtual user has its own unique session.

The session plays a critical role in managing dynamic data—like session IDs, authentication tokens, user credentials, or order numbers—that may change from one request to another. This capability enables the simulation of realistic workflows where each request depends on the outcome or data from previous interactions.

At its core, the session behaves like a Map<String, Object>, and the entries within this map are referred to as session attributes. These attributes can be stored, retrieved, or updated as the scenario progresses, making sessions a powerful feature for customizing and controlling virtual user behavior throughout the test lifecycle.



The Basics of the Session API

The session API in Gatling provides a set of methods that allow you to read, write, and manipulate session variables dynamically. The session is available at every point in a scenario, making it an essential part of simulating stateful user interactions and enabling the flow of data across multiple requests or actions within a test.

Setting Session Attributes

We can set session attributes using the set and setAll methods. These methods return a new session instance with the updated attributes, leaving the original session unmodified. This immutability allows for better management of data throughout the test, ensuring that each simulation step starts with a clean, consistent session. By using these methods, you can maintain precise control over how data is updated and passed between requests, facilitating more accurate and reliable load testing scenarios. This approach promotes cleaner, easier-to-manage test scripts while preserving the integrity of the session data throughout the simulation.

Set a single attribute

Session newSession1 = session.set("key", "value");

Set multiple attribute

Session newSession2 = session.setAll(Map.of("key", "value"));

Retrieving Session Attributes

To retrieve session attributes, you can use various getter methods provided by Session API.

Check if an attribute is stored in the session

boolean contains = session.contains("key");

Get an attribute value and cast it

String string = session.getString("key");

Get an int attribute (will throw if it's null)

 int primitiveInt = session.getInt("key");

Get an Integer attribute

Integer intWrapper = session.getIntegerWrapper("key");

Get a long attribute (will throw if it's null)

long primitiveLong = session.getLong("key");

Get a Long attribute

Long longWrapper = session.getLongWrapper("key");

Get a Boolean attribute (will throw if it's null)

boolean primitiveBoolean = session.getBoolean("key");

Get a Boolean attribute

Boolean booleanWrapper = session.getBooleanWrapper("key");

Get a double attribute (will throw if it's null)

double primitiveDouble = session.getDouble("key");

Get a Double attribute

Double doubleWrapper = session.getDoubleWrapper("key");

Get an attribute value and cast it into a List

List<MyPojo> list = session.getList("key");

Get an attribute value and cast it into a Set

Set<MyPojo> set = session.getSet("key");

Get an attribute value and cast it into a Map

Map<String, MyPojo> map = session.getMap("key");

Get an attribute value and cast it

MyPojo myPojo = session.get("key");

Removing Session Attributes

We can remove session attributes using the remove and removeAll methods. These methods also return a new session instance with specified attributes removed

Removes a single attribute

Session newSession = session.remove("key");

Removes multiple attributes

Session newSession = session.removeAll("key1", "key2");

Removes all non gatling internal internal attributes

Session newSession = session.reset();

Practical Examples of Using Session API

Using session API while creating request body

Suppose we have defined our request model class like


Where getRandomEmail() and getRandomMobileNumber() generates random email and mobile number using a custom implementation. We can directly use the request model in session API.

Each virtual user will now be assigned a unique, randomly generated mobile number and email. 

Let's explore another approach to pass the email and mobile number. To do this, we'll create a separate method that returns a session, and then use it to inject the mobile number and email values into the simulation.


We have saved two variables email and mobile inside the session.We can access these stored variables using session.getString(“email”) and session.getString(“mobile”) or using gatling dsl “#{email}” and “#{mobile}” .

Using session.getString() inside chainbuilder.

This is how our scenario builder will look in this case.

exec(session -> carsClient.sessionApiExample(session)): This code sets the value of email and mobile in the session which can then be used using session.getString() or using galing dsl.

exec(carsClient.sessionAPIExample1())): This code will execute the API with the values stored in session.

Alternatively, we can pass email and mobile directly using gatling dsl.



Using session API with checkIf()

Using session API, we can check for a condition in response body and then perform some action like.


The above request checks for a 201 Created status code and saves the email field from the response into the session as emailAddress. If the emailAddress contains the string "random", it further saves the mobile field from the response into the session as mobileNumber.


The above request checks for the email field in the response and saves it into the session as emailAddress. If the emailAddress contains the string "random" and the response status code is 201, it further saves the mobile field from the response into the session as mobileNumber.

The Gatling Session API is a powerful tool that enables you to simulate complex, stateful user behavior in your load testing scenarios. By effectively using session variables, you can create dynamic, realistic tests that better reflect actual user interactions with your application. Whether you're handling authentication tokens, managing session data across multiple requests, or looping based on session variables, the Session API is central to ensuring your performance tests are robust and accurate.

By understanding and leveraging the full potential of the Session API, you can take your load testing skills to the next level and ensure your applications can handle real-world traffic efficiently. The Session API empowers you to simulate realistic, stateful user interactions by managing and passing dynamic data between different requests. Whether you're handling authentication tokens, session identifiers, or user-specific inputs, the Session API gives you the flexibility to create complex testing scenarios that closely mirror actual user behavior. Mastering this feature is key to building robust, reliable performance tests. The complete source code and examples can be found in my github repository.

Happy testing!🚀



Post a Comment

Previous Post Next Post