Problem statement
Support cannot trace a request across logs because nothing ties log entries and responses together, even when requests fail. Complete CorrelationIdMiddleware and register it as the first stage of the request pipeline, so that every request is given a correlation id, every stage and every endpoint behind it reads that same id, and every response carries it back in the X-Correlation-ID header, including the answers the pipeline itself produces when the request never reaches an endpoint.
Sample Data
The API is pre-seeded with three orders, held in memory. Here is an example of an Order JSON object:
{
"id": 2,
"customer": "Globex",
"amount": 80.50,
"status": "shipped"
}
The listing returns them ordered by id. A stored order receives the next id after the ones already held, and the status open.
Service
The Pipeline
Program builds the pipeline from six calls, in this order, and they stay exactly as they are: UseRequestTiming, UseErrorHandling, UseMaintenanceMode, UseRouting, UseApiKeyGate and UseEndpoints. No call is removed, and no call is added beyond the one you register.
Each request resolves its own ICorrelationIdAccessor, whose CorrelationId starts as null and is the single place every stage and every endpoint of that request reads the id from. Each of them also records its own name, and the id it can read at that moment, in IPipelineTrace, so a stage running ahead of the correlation stage records no id at all.
Not every answer comes from an endpoint. The maintenance stage answers 503 by itself while its switch is on, the key gate refuses an unauthorized caller with 401, the error stage converts a failure raised behind it into 500, and routing answers 404 for a path no endpoint serves. Each of those answers carries a correlationId of its own, and the timing stage logs the id with every request.
CorrelationIdMiddleware
Implement InvokeAsync, which receives the request and the ICorrelationIdAccessor of that request:
- InvokeAsync:
- Settle the correlation id of the request. When the request carries an X-Correlation-ID header holding a value that is not blank, that value is the correlation id, used exactly as it arrived. Surrounding spaces and the letter case of that value are part of it, so it is neither trimmed nor changed in case before it is published to the stages behind the correlation stage and sent back on the response.
- Generate an id when the header is absent, or holds an empty or whitespace-only value, since a blank value counts as no id at all. A generated id is a new globally unique identifier in its 36 character form with four dashes, and each request that needs one gets its own freshly generated id.
- Publish the id on ICorrelationIdAccessor before handing the request on, so every stage and every endpoint behind the correlation stage reads that same value.
- Always invoke the rest of the pipeline, for every request. The correlation stage never short circuits, and it never changes the status code, the body or any other header the rest of the pipeline produced.
- Make sure the response carries the id in the X-Correlation-ID response header, once, with that single value, whatever the rest of the pipeline did with the request. That covers the answers an endpoint produced, the 404 for a path no endpoint serves, the 401 from the key gate, the 503 from the maintenance stage and the 500 the error stage builds.
- Attach the header as the response starts, rather than writing it straight onto the response on the way in. The error stage throws the half-built response away and rebuilds it from nothing before writing its answer, so a header written on the way in is no longer there by the time the error answer is sent, while one attached as the response starts survives.
Program
- Main:
- Register CorrelationIdMiddleware in front of all six pipeline calls, so the id is settled before the timing stage logs it, before the error stage builds an error answer, before the maintenance stage answers on its own, and before routing decides whether the path is served at all.
Sample Requests & Responses
Every answer below carries the response header X-Correlation-ID holding the id that request settled on, and every trace entry carries that same id. The calls all send X-Correlation-ID: support-4821 unless they say otherwise.
GET /api/orders
Response code: 200
[
{ "id": 1, "customer": "Acme", "amount": 250.00, "status": "open" },
{ "id": 2, "customer": "Globex", "amount": 80.50, "status": "shipped" },
{ "id": 3, "customer": "Initech", "amount": 15.00, "status": "open" }
]
Trace: timing, error:entered, maintenance:passed, apikey:not-required, endpoint:orders-list:started, endpoint:orders-list:completed
Log entry from the timing stage: HTTP GET /api/orders responded 200 in 4 ms with correlation id support-4821
Where the id comes from:
- Sent with no X-Correlation-ID header, the answer carries a generated one such as 6f5f4d09-6a26-4a1e-8f2c-2e0f3f9d2b41, and the next such request gets a different one again.
- Sent with the header holding only spaces, a blank value counts as no id at all, so one is generated the same way.
The other calls, each answering with the id it was sent:
- GET /api/diagnostics/echo answers 200 reporting the id it read for itself, which is how a downstream component proves it observed the same id the response carries.
- GET /api/orders/2 answers 200 with that order, while GET /api/orders/99 answers 404 with a message of Order 99 was not found.
- POST /api/orders answers 201 with the stored order, while an amount of 0 answers 400 with a message of Amount must be greater than zero. and stores nothing.
- GET /no-such-path is answered 404 by routing, and still carries the id.
- GET /api/reports/daily with X-Api-Key: support-desk-key answers 200, its trace reading timing, error:entered, maintenance:passed, apikey:accepted, endpoint:reports-daily:started, endpoint:reports-daily:completed.
- The same call with no key, or with a key the gate does not know, answers 401 with WWW-Authenticate: ApiKey and an error of An operator key is required for this endpoint., its trace ending at apikey:challenged with no endpoint entry because the endpoint never ran.
- GET /api/diagnostics/fail answers 500 with an error of Unhandled server error: the endpoint records that it started and then fails, and the error stage throws the half-built response away and writes its own, the id still reaching the answer. Its trace reads timing, error:entered, maintenance:passed, apikey:not-required, endpoint:diagnostics-fail:started, error:converted, and the timing stage logs HTTP GET /api/diagnostics/fail responded 500 in 3 ms with correlation id support-4821.
- While the maintenance switch is on, GET /api/orders and GET / are both answered 503 with the maintenance notice, the trace holding no endpoint entry. Once it is off again, GET / answers 200 as before.
