Troubleshooting errors in a production environment sucks. Even when end users aren’t directly impacted, there’s still usually a huge amount of pressure to figure out what is going wrong, and fast. One of the nicer tools to assist with this troubleshooting is AWS X-Ray.
AWS X-Ray helps developers analyze and debug production, distributed applications , such as those built using a microservices architecture.
https://aws.amazon.com/xray/
I’m not going to go into great detail about X-Ray itself in this post, but the end goal is to have trace logs and a generated graphical mapping of interacting services, as well as being able to drill into where errors are happening. X-Ray is different from CloudWatch, as CloudWatch is for logs and metrics for individual applications. Meanwhile, X-Ray specifically focuses on the tracing between applications.
With the release of .NET Core 2.1 came an HttpClientFactory, along with typed HttpClients. Steve Gordon has an excellent blog series covering typed HttpClients. I wanted a way to seamlessly integrate typed HttpClients into AWS X-Ray. After a bit of poking around, I discovered HttpClientXRayTracingHandler in the AWS X-Ray SDK. HttpClientXRayTracingHandler implements HttpClientHandler, which can be leveraged in conjunction with these typed clients. After registering the HttpClientXRayTracingHandler, you can add it as a handler with your typed client as follows:
services.AddTransient<HttpClientXRayTracingHandler>();
services.AddHttpClient<IMyGitHubClient, MyGitHubClient>()
.AddHttpMessageHandler<HttpClientXRayTracingHandler>();
You still have to configure the rest of your start up with these additions:
// Inititalizing Configuration object with X-Ray recorder
AWSXRayRecorder.InitializeInstance(configuration: Configuration);
// All AWS SDK requests will be traced
AWSSDKHandler.RegisterXRayForAllServices();
//In your configure method
app.UseXRay("XRayServerless");
//In your appsettings.json:
/*
"XRay": {
"DisableXRayTracing": "false",
"UseRuntimeErrors": "true"
}
*/
X-Ray displays the traces for the actual HTTP calls once everything is configured:

These traces are nice, but the best part is the generated Service Map:

After clicking the ApiGateway, I can see that the endpoint hit ends in “/Prod/%7Bproxy+%7D” which is the pseudo-endpoint for .NET Core lambda functions, how it passes the requests to the .NET Core routing. Since it isn’t a real endpoint, it returns a 404. Note: X-Ray is also enable on the ApiGateway that’s in front of the lambda function.
I put together a quick demo project that pulls in the X-Ray Recorder nuget package and wires up the necessary components to do the tracing, so you can try it out yourself quickly. You can find it here:
https://github.com/mvalenta/XRayServerlessDemo