Tracing Grails requests with OpenTelemetry

When a Grails request becomes slow, logs can show an exception while hiding the operation that consumed the time. OpenTelemetry supplies a shared tracing model for the whole request path, linking the controller, Groovy service code, GORM queries, outbound HTTP calls, and queue operations under one trace identifier. The Grails Example lessons provide a useful foundation for the Grails and Groovy side of that path.

Most teams begin with automatic instrumentation because it captures common framework behaviour with little application code. The Java agent recognises servlet requests, Spring components used by Grails, JDBC and Hibernate activity, and supported HTTP clients. Manual spans then explain business operations that the agent cannot infer. This split gives you broad coverage quickly while keeping domain language visible where teams need it.

A useful trace should answer more than which endpoint was called. It should reveal where latency accumulated, whether a database call became chatty, and how an external provider influenced the response. The same trace ID can be carried into structured logs, so an engineer can move from an alert to the exact request path without guessing from timestamps or matching separate log lines.

Start in a representative environment and preserve the signals you already rely on. Sydney and Melbourne teams commonly run workloads in AWS ap-southeast-2, Azure Australia East, or Google Cloud’s australia-southeast1 region, yet trace exports still need an explicit data-residency decision. Australian privacy expectations and customer contracts can restrict where telemetry leaves the cluster, so a local OpenTelemetry Collector is often the safest first hop.

Build a simple tracing path

OpenTelemetry separates instrumentation from storage. Your Grails application emits OTLP data to an OpenTelemetry Collector, which batches, filters, and exports traces to a backend such as Tempo, Jaeger, or another observability platform. The collector is valuable even for a small team: application containers do not need direct credentials for the tracing vendor, and the same routing layer can serve development, staging, and production.

Keep the first architecture deliberately small: one Grails service, one collector, one trace backend. Add an ingress or load balancer only when you need its identity in the trace. If a proxy participates in the request, capture its hop through supported instrumentation rather than inventing a second trace. That preserves parent-child relationships and avoids fragmented waterfalls.

Agree on service naming before dashboards become crowded. Use stable names such as orders-api, billing-worker, and customer-portal; put mutable values such as environment, version, and region in resource attributes. Separate each environment’s pipeline and apply access controls early, especially where an Australian customer requires telemetry to remain in an approved jurisdiction.

Attach the OpenTelemetry Java agent

The Java agent is the quickest route to a complete baseline. Confirm that its supported Java and Grails stack matches your application, then download the agent bundle and keep its version under configuration control. The agent instruments libraries before the application starts, so an endpoint handled by Grails can appear in a trace even when the controller contains no tracing code.

Attach it to the JVM that serves the request. For an executable Grails artifact, the command can look like this, with the filename adjusted for your build:

export OTEL_SERVICE_NAME=orders-api
export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=1.0
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=staging,service.version=1.4.0

java -javaagent:/opt/opentelemetry/opentelemetry-javaagent.jar \
  -jar build/libs/orders-api.war

If you start the application with bootRun, place the same -javaagent option in JAVA_TOOL_OPTIONS. The collector’s OTLP HTTP receiver commonly listens on port 4318, while 4317 is used for gRPC. Use HTTP/protobuf where a firewall or platform favours HTTP, and protect the endpoint with network rules or authentication. When Grails runs inside an external servlet container, attach the agent to that container’s JVM rather than to a one-off Gradle process that is not serving traffic.

Read the request waterfall

Once traces arrive, begin with the server span and walk down the hierarchy. A typical Grails request may contain a controller span, a domain-service span, one or more GORM or JDBC spans, an HTTP-client span for a payment provider, and a final rendering segment. The ordering shows critical-path duration, while parentage shows which work belonged to the original request.

Pay attention to repeated database work as well as individual slow statements. One span taking 400 milliseconds is easy to spot; twenty quick queries inside a service may reveal an N+1 pattern that matters more. External calls need their own interpretation: a fast failed connection can be more actionable than a slow successful response, especially when retries occur upstream.

Trace visuals are often reviewed in screenshots as well as live dashboards. When you capture a busy waterfall for a team review, the rule of thirds can help keep the busiest region visible without hiding the surrounding context. Add the trace ID and environment to the capture, and link it to the relevant deployment so the evidence remains understandable weeks later.

Add spans around business work

Automatic instrumentation sees framework calls, but it cannot know that placing a reservation is the important part of an orders workflow. Create manual spans around domain operations such as pricing a basket, validating eligibility, or reserving stock. Give them stable, low-cardinality names and attach business attributes that help triage the operation.

The following Groovy example uses the OpenTelemetry API exposed through the agent. Add the API dependency at a version compatible with your agent, then wrap the operation in a scope so any nested instrumented calls inherit the current span:

import io.opentelemetry.api.GlobalOpenTelemetry
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.SpanKind
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.context.Scope

Tracer tracer = GlobalOpenTelemetry.getTracer("com.example.orders")
Span span = tracer.spanBuilder("inventory.reserve")
        .setSpanKind(SpanKind.INTERNAL)
        .startSpan()

try (Scope ignored = span.makeCurrent()) {
    span.setAttribute("orders.item_count", itemCount)
    reserveStock(itemCount)
} catch (Exception exception) {
    span.recordException(exception)
    span.setStatus(StatusCode.ERROR, exception.getMessage())
    throw exception
} finally {
    span.end()
}

Set attributes while the operation is active, and record failures before rethrowing them. The agent can capture stack traces and HTTP or JDBC errors, while the manual span preserves the business context that generic instrumentation lacks. Avoid attaching a user, an order identifier, or other high-cardinality value to the span name; keep names reusable and put approved identifiers in attributes only when your retention policy permits.

Preserve context across service boundaries

Context propagation is what turns separate spans into one trace. OpenTelemetry uses W3C headers, principally traceparent and tracestate, to carry the active trace across HTTP calls. The Java agent normally injects these headers into supported outbound requests and extracts them from inbound requests, but gateways, proxies, and custom filters must not strip or rewrite them accidentally.

Test the path with a curl request that includes a valid traceparent header, then inspect the inbound server span in the backend. If the sample shows a new root trace, check the load balancer and application filters. If child spans appear under an unexpected parent, inspect the gateway hop and any service-mesh routing rules rather than changing span code in the controller.

Threads create a second common break. A Grails async controller, custom ExecutorService, or background task can lose the active context when work moves away from the request thread. Preserve the OpenTelemetry context at the handoff, or use framework-aware instrumentation, so the asynchronous work remains attached to the business operation. For message queues, carry trace headers in message metadata and extract them before processing begins.

Operate tracing without creating noise

Sampling is the main control over trace volume and cost. Use the parentbased_traceidratio sampler so an upstream decision remains consistent across services. Sample every trace in development and staging, then choose a modest production ratio based on traffic and diagnostic needs. A percentage that is tiny for a busy checkout service may still be substantial across dozens of microservices.

Logs and traces should share identifiers. Configure the OpenTelemetry Logback or Log4j instrumentation to place the trace ID and span ID in the logging context, then include those fields in the log pattern. An operator can search a trace ID in the tracing backend or search the same value in logs without relying on clocks being perfectly synchronised.

Treat telemetry as production data. Redact authorisation headers, cookies, request bodies, and sensitive business fields, and review whether database statements contain personal information. Configure collectors to use TLS and authentication, limit which networks can submit OTLP, and apply retention rules that match customer expectations. The collector’s memory limiter, retry queue, and batch processor protect the application from slow trace backends.

Operational timing adds another Australian wrinkle: Perth, Sydney, and Brisbane sit on different clock offsets, and daylight-saving changes can make a short incident appear to span an extra hour. Record timestamps in UTC and display the local zone at the point of review. During a quick arvo handover between western and eastern teams, include the deployment version and trace sample in the notes. Cloud trace and egress charges can also exceed an unbudgeted monthly bill, so sample deliberately and monitor exporter volume.


Deploy the agent to one low-risk Grails service in staging, export to a local collector, and send a traceparent header through the service. Save the resulting trace ID in the team runbook. That single repeatable exercise turns OpenTelemetry from an unfamiliar library into an operational tool the team can use during the next incident.

Choose one representative endpoint, define the service and environment attributes, and put the collector behind the same access controls as the application. Make the first trace part of the normal debugging workflow today.