Simmy Chaos Engine for .NET – Part 3, Adding Latency

Full source code here.

Want to learn more about Polly? Check out my Pluralsight course on it.

This is the third in my series on chaos engineering with Simmy. The first two posts dealt with the fault policy throwing exceptions and returning failed responses rather than calling the remote service.

In this I will show how to use the latency policy to inject delays into requests. It works in a similar way to the fault policy - a delay is chosen, the percentage of the time the delay should apply is chosen, and finally the policy is enabled/disabled.

When the policy is active, it delays the request, not the response.

1var latencyPolicy = MonkeyPolicy.InjectLatencyAsync<HttpResponseMessage>(
2    TimeSpan.FromSeconds(5), // inject a 5 second delay
3    0.5, // in 50% of requests
4    () => true); // policy is enabled

To see the effect of the latency policy I am going to add Polly timeout policy that throws an TimeoutRejectedException if no response is received from the OpenBreweryDb in 2 seconds.

I have also added a Polly retry policy to retry request that fail or timeout.

1IAsyncPolicy<HttpResponseMessage> timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(2); 

The retry policy is set to retry up to three times.

1IAsyncPolicy<HttpResponseMessage> retryPolicy = Policy
2                .HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
3                .Or<Exception>()
4                .RetryAsync(3)

I have a policy wrap with the latency policy at the center, the timeout around it and finally the retry around that.

1IAsyncPolicy<HttpResponseMessage> latencyTimeoutAndRetryPolicy = Policy.WrapAsync(
2    retryPolicy, timeoutPolicy, latencyPolicy);

What happens is - In 50% of the requests to the OpenBreweryDb, the latency policy delays the request by 5 seconds. If the latency is active, the timeout policy throws a TimeoutRejectedException. Then retry policy retries the request again.

If you run the application you will see the timeout and retry policies logging to the console.

That’s it, the latency policy is very easy to use.

Full source code here.

comments powered by Disqus