Generate request tracing headers
Verified Code examples on this page have been automatically tested and verified.Use the uuid() and random() CEL functions to inject dynamically generated values into request headers. uuid() generates a unique UUIDv4 string on each request, useful for correlation IDs in distributed tracing. random() returns a float between 0.0 and 1.0, useful for probabilistic sampling decisions.
Before you begin
- Set up an agentgateway proxy.
- Install the httpbin sample app.
Generate request tracing headers
Tracing every request can be expensive at high traffic volumes. A common pattern is to inject a unique ID for correlation and a random value that a downstream tracing backend uses to decide whether to record a full trace, keeping only a percentage of all requests.
In this example, two headers are injected on every incoming request before it is forwarded upstream:
x-request-id: A unique UUIDv4 generated byuuid(), used to correlate the request across services.x-sampling-decision: A random float from therandom()function. For example, you might have a tracing backend that is configured to sample requests only if thex-sampling-decisionheader is set to0.1or less.
Create an AgentgatewayPolicy resource with your transformation rules.
kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayPolicy metadata: name: transformation namespace: httpbin spec: targetRefs: - group: gateway.networking.k8s.io kind: HTTPRoute name: httpbin traffic: transformation: request: set: - name: x-request-id value: 'uuid()' - name: x-sampling-decision value: 'string(random())' EOFThe expression breaks down as follows:
uuid(): Generates a new UUIDv4 string for each request, such asf47ac10b-58cc-4372-a567-0e02b2c3d479.random(): Generates a random float between0.0and1.0, such as0.4731. Wrap the transformation instring()so the value can be set as a header string.
Send a request and verify that both headers are present in the forwarded request.
curl -vi http://$INGRESS_GW_ADDRESS:80/get \ -H "host: www.example.com:80"curl -vi localhost:8080/get \ -H "host: www.example.com"Example output:
< HTTP/1.1 200 OK HTTP/1.1 200 OK ... { "headers": { "X-Request-Id": [ "81895ac3-0b2b-45cb-901d-068b517c7262" ], "X-Sampling-Decision": [ "0.32929987260956217" ] ... }, ... }Each request produces a different
X-Request-Idvalue. TheX-Sampling-Decisionvalue varies between0.0and1.0on each request.
Cleanup
You can remove the resources that you created in this guide.kubectl delete AgentgatewayPolicy transformation -n httpbin