Retry HTTP request based on HTTP status code

Hello,

I am trying to add a simple retry if the response from the server is for example a 504 (gateway error).

Ideally, I would like to retry with some delay between attempts.

I can do a basic (blind) tryMax:

exec(
      tryMax(3)(
            http(f"MyRequest")
              .post(session => session("url").as[String])
              .headers(headers)
              .header("User-Agent", session => session("id").as[String])
              .body(StringBody(session => session("request").as[String]))
              .requestTimeout(1.minutes)
              .check(status.is(200))
          )
    )
      .doIf(session => session.status == KO)(
        stopInjector(session => f"KO ${session("id").as[String]}")
      )

But I am not sure how to take the status code into account.

Not sure what your question is. Your current code will retry every time the status is not 200 or an error happens (eg connection failure). Isn’t it sufficient for your needs?
Or do you want to only trigger the retry on 504?

Hi @jonathan.naguin,

You can save the status in the session, so you can use it later.

  val myPostRequest = http("MyRequest")
    .post("#{url}")
    .headers(headers)
    .header("User-Agent", "#{id}")
    .body(StringBody("#{request}"))
    .requestTimeout(1.minutes)
    .check(status.is(200).saveAs("lastStatus")) // Save the status for later usage

  val scn = scenario("Test")
    .exec(
      tryMax(2)( // 3 max try minus 1 already done
        myPostRequest
      ),
      doIf(_.isFailed)(
        stopInjector("My last status was #{lastStatus}")
      )
    )

And about the delay between attempts, you can add pauses, but perhaps you want to add pause only if the first try failed?

  val scn = scenario("Test")
    .exec(
      myPostRequest,
      doIf(_.isFailed)(
        tryMax(2)( // 3 max try minus 1 already done
          exec(_.markAsSucceeded), // Clear previous failure
          pause(10.seconds, 30.seconds, exponentialPauses),
          myPostRequest
        )
      ),
      doIf(_.isFailed)(
        stopInjector("My last status was #{lastStatus}")
      )
    )

Does that helps?

Cheers!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.