Tracing Requests
Understand how to trace requests in your REST API application of Athenna.
Introduction
Briefly, tracing represents a single user's journey through an entire app stack. By tracing through a stack, developers can identify what happened with determined request and also identify bottlenecks and focus on improving performance.
Looking for distributed tracing with OpenTelemetry, spans and trace IDs shared across multiple applications? Check the REST API observability documentation.
Basic usage
Every request handled by Athenna has a unique ID. This ID
is generated by Fastify and it's available in the request.id
property of your routes:
import { Log } from '@athenna/logger'
import { Route } from '@athenna/http'
Route.get('/', ({ request }) => {
Log.info(request.id) // req-1
return 'Hello World!'
})
By default, Fastify generates a sequential ID for each request
of the process (req-1, req-2, req-3...). This is fine to
correlate all the logs of a single request, but it's not unique
between different instances of your application.
Customizing the request ID
All the options of the http.fastify object inside your
Path.config('http.ts')./src/config/http.ts
genReqId
option to generate the IDs the way you want, like using
a UUID:
import { randomUUID } from 'node:crypto'
export default {
fastify: {
genReqId: () => randomUUID()
}
}
Route.get('/', ({ request }) => {
Log.info(request.id) // 123e4567-e89b-12d3-a456-426614174000
})
Using the request ID sent by the client
If your application is behind a load balancer or an API gateway
that already generates an ID for the request, you can tell
Fastify to reuse it with the
requestIdHeader
option. When the header is not present, the genReqId function
is used as fallback:
import { randomUUID } from 'node:crypto'
export default {
fastify: {
requestIdHeader: 'x-request-id',
genReqId: () => randomUUID()
}
}
Only trust the request ID header if it's set by a component that you control, like your load balancer. Otherwise any client could send the ID they want.