Skip to main content

XUnit - Simulate concurrency and load against an API endpoint

Today I was working on an ASP.NET Core Web API that implements rate limiting. The ASP.NET Core Web API should still accept the incoming requests but the handling of the requests should be buffered when the rate limits where exceeded. Maybe I’ll share how I implemented this in another blog post, but in this post I want to focus on how I tested this functionality.

My first idea was to use Parallel.For() to generate a lot of concurrent requests. You would think it would generate a number of request using the specified or calculated degree of parallelism.  Unfortunately that is not the case. Instead, all the tasks are started at the same time.

var options = new ParallelOptions() {
MaxDegreeOfParallelism = 2
};
Parallel.For(0, 10, options, async i => await ExecTask(i));
view raw ParallelFor.cs hosted with ā¤ by GitHub

In the example above all 10 tasks are started at the same time.

Another issue is that Parallel.For() doesn’t wait for the started tasks to finish which would result in the completion of the test without waiting for the results.

So we need to find another way to achieve our goal. I got what I want by using a combination of Task.WhenAll() and SemaphoreSlim to limit the concurrency.

using System;
using System.IO;
using System.Linq;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
using Xunit.Abstractions;
namespace API.Tests
{
public class PerformanceTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _fixture;
private readonly ITestOutputHelper _testOutputHelper;
const int MAX_DEGREE_OF_PARALLELISM = 2;
static SemaphoreSlim _semaphore = new SemaphoreSlim(MAX_DEGREE_OF_PARALLELISM);
public PerformanceTests(WebApplicationFactory<Program> fixture, ITestOutputHelper testOutputHelper)
{
_fixture = fixture;
_testOutputHelper = testOutputHelper;
}
[Fact]
public async Task Send_A_Lot_Of_Requests()
{
//Arrange
var message=new Message();
//Act
var tasks = Enumerable.Range(0, 12)
.Select(i => ExecTask(i, message))
.ToArray();
await Task.WhenAll(tasks);
}
async Task<int> ExecTask(int index, Message mail)
{
await _semaphore.WaitAsync();
try
{
var client = _fixture.CreateClient();
_testOutputHelper.WriteLine($"{index} - Sending request");
await mailClient.PostAsJsonAsync("/example/", message);
_testOutputHelper.WriteLine($"{index } - Request sent");
return index;
}
finally
{
_semaphore.Release();
}
}
}
}
view raw PerformanceTests.cs hosted with ā¤ by GitHub

Popular posts from this blog

Kubernetes–Limit your environmental impact

Reducing the carbon footprint and CO2 emission of our (cloud) workloads, is a responsibility of all of us. If you are running a Kubernetes cluster, have a look at Kube-Green . kube-green is a simple Kubernetes operator that automatically shuts down (some of) your pods when you don't need them. A single pod produces about 11 Kg CO2eq per year( here the calculation). Reason enough to give it a try! Installing kube-green in your cluster The easiest way to install the operator in your cluster is through kubectl. We first need to install a cert-manager: kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.5/cert-manager.yaml Remark: Wait a minute before you continue as it can take some time before the cert-manager is up & running inside your cluster. Now we can install the kube-green operator: kubectl apply -f https://github.com/kube-green/kube-green/releases/latest/download/kube-green.yaml Now in the namespace where we want t...

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

.NET 9 - Goodbye sln!

Although the csproj file evolved and simplified a lot over time, the Visual Studio solution file (.sln) remained an ugly file format full of magic GUIDs. With the latest .NET 9 SDK(9.0.200), we finally got an alternative; a new XML-based solution file(.slnx) got introduced in preview. So say goodbye to this ugly sln file: And meet his better looking slnx brother instead: To use this feature we first have to enable it: Go to Tools -> Options -> Environment -> Preview Features Check the checkbox next to Use Solution File Persistence Model Now we can migrate an existing sln file to slnx using the following command: dotnet sln migrate AICalculator.sln .slnx file D:\Projects\Test\AICalculator\AICalculator.slnx generated. Or create a new Visual Studio solution using the slnx format: dotnet new sln --format slnx The template "Solution File" was created successfully. The new format is not yet recognized by VSCode but it does work in Jetbr...