Session & Correlation¶
Every virtual user in Gatling carries its own isolated Session—an immutable, thread-safe key-value map holding feeder attributes, cookies, auth tokens, and correlated IDs extracted from previous responses.
1. The #1 Gatling Pitfall: Session Immutability¶
io.gatling.javaapi.core.Session is strictly immutable (like Java's String or BigDecimal). Every mutation method (set, setAll, remove, markAsFailed) returns a brand-new Session instance!
2. End-to-End Dynamic Correlation¶
Correlation links stateful steps together—extracting dynamic server-generated values (JWTs, CSRF tokens, created entity IDs, ETags) via .check(...saveAs(...)) and injecting them into subsequent requests:
sequenceDiagram
participant F as CSV Feeder
participant S as Virtual User Session
participant API as E-Commerce API
F->>S: userId="u-42", password="secret"
S->>API: 1. POST /auth/login (#{userId})
API-->>S: 200 OK {"accessToken": "eyJhbG..."}
Note over S: saveAs("jwt")
S->>API: 2. POST /cart (Authorization: Bearer #{jwt})
API-->>S: 201 Created {"cartId": "c-998"}
Note over S: saveAs("cartId")
S->>API: 3. POST /checkout ({"cartId": "#{cartId}"})
API-->>S: 200 OK {"orderId": "ord-777"}
ScenarioBuilder correlatedCheckout = scenario("Stateful Checkout")
.feed(csv("data/users.csv").circular())
// Step 1: Authenticate & capture JWT
.exec(http("1. Login")
.post("/auth/login")
.body(StringBody("{\"username\": \"#{username}\", \"password\": \"#{password}\"}"))
.check(status().is(200), jsonPath("$.accessToken").saveAs("jwt")))
// Step 2: Create Cart using correlated Bearer token
.exec(http("2. Create Cart")
.post("/cart")
.header("Authorization", "Bearer #{jwt}")
.body(StringBody("{\"sku\": \"SKU-100\", \"qty\": 1}"))
.check(status().is(201), jsonPath("$.cartId").saveAs("cartId")))
// Step 3: Guarded Checkout — only execute if Step 2 succeeded and saved cartId!
.doIf(session -> session.contains("cartId")).then( // (1)!
exec(http("3. Checkout")
.post("/checkout/#{cartId}")
.header("Authorization", "Bearer #{jwt}")
.check(status().is(200)))
);
- Pro Tip: If Step 2 fails (
HTTP 500),cartIdis never saved! Without.doIf(session -> session.contains("cartId"))(or.exitHereIfFailed()), Step 3 will firePOST /checkout/#{cartId}literally or fail with"No attribute named 'cartId' is defined", creating noisy secondary cascading failures in your report!
3. Preventing Cascading Failures with exitHereIfFailed()¶
In stateful workflows (Login $\rightarrow$ Cart $\rightarrow$ Payment), continuing a virtual user's journey after Login fails makes zero business sense and pollutes downstream endpoint error metrics:
ScenarioBuilder cleanFailureHandling = scenario("Guarded Journey")
.exec(http("Login").post("/auth/login")
.check(status().is(200), jsonPath("$.token").saveAs("token")))
.exitHereIfFailed() // Aborts this virtual user immediately if Login failed!
.exec(http("Protected Profile").get("/me")
.header("Authorization", "Bearer #{token}"));
Typed Session API Cheat Sheet¶
| Operation | Java Session Method |
|---|---|
Read String |
String id = session.getString("userId"); |
Read int / double / boolean |
int qty = session.getInt("qty"); |
Read List<T> |
List<String> ids = session.getList("ids"); |
| Check attribute presence | boolean hasToken = session.contains("jwt"); |
| Check if any prior check failed | boolean ko = session.isFailed(); |
| Store single value | return session.set("key", value); |
| Store map of values | return session.setAll(Map.of("k1", v1, "k2", v2)); |
| Remove attribute (free RAM) | return session.remove("largePayload"); |
Knowledge Check¶
If POST /auth/login returns HTTP 503 and fails to extract jwt, what happens on the next step (GET /orders with header Bearer #{jwt}) if you did NOT call .exitHereIfFailed() or .doIf(session -> session.contains("jwt"))?
Next Steps¶
- Hands-On Practice: Lab Overview — Put protocols, feeders, checks, correlation, and Kafka producers into action!
- Observability: Datadog Integration — Correlate Gatling simulations with distributed APM traces.