Audit Grails request timing with interceptors

Request timing turns a vague complaint about a slow endpoint into evidence a team can act on. In a Grails application, an interceptor can capture when a controller request begins, how long it runs, which HTTP status it returns, and whether it failed. That audit trail helps developers separate slow business logic, database waits, rendering costs, and upstream network delays while the request is still fresh.

A Grails interceptor is a natural fit because it surrounds controller actions without scattering timing calls through domain services. It also gives Java developers coming to Groovy a familiar cross-cutting concern: one component observes a request before and after the action, while the controller remains focused on its task. The result is a consistent request-duration log or audit stream that can feed dashboards, alerts, and later performance investigations.

What request timing reveals

Timing an API call is more useful when the event contains context. A duration without a route, method, status code, or request identifier is difficult to search and easy to misread. Keep the controller action stable, record the elapsed milliseconds, and attach a unique request ID so every log line, downstream call, and support ticket can be joined to the same event.

Measure elapsed time with System.nanoTime() rather than subtracting two wall-clock timestamps. Monotonic time avoids surprises when a server clock is adjusted by network time protocol synchronisation. Instant.now() still belongs in the event as an absolute timestamp, but it should describe when the request happened; it should not be the stopwatch used to calculate duration.

Choose the boundary deliberately. A controller interceptor can report action execution, action-plus-view processing, or a broader application window. Those values answer different questions and should have distinct names in the audit record. The phrase “request timing” is useful shorthand, yet the exact boundary must be documented before a team compares one release with another.

Building a practical timing interceptor

Place the interceptor under grails-app/interceptors and inject the component that will publish the result. The following example uses a service named auditRecorder; in a larger application, that service could write to a database, emit structured JSON, or forward the event to a queue.

import java.time.Instant

class RequestTimingInterceptor {

    RequestTimingInterceptor() {
        matchAll()
    }

    def auditRecorder

    boolean before() {
        request.setAttribute('audit.startNanos', System.nanoTime())
        request.setAttribute('audit.startedAt', Instant.now())
        request.setAttribute('audit.requestId', UUID.randomUUID().toString())
        true
    }

    void afterView() {
        recordAudit(null)
    }

    boolean after(Throwable failure) {
        recordAudit(failure)
        false
    }

    private void recordAudit(Throwable failure) {
        if (request.getAttribute('audit.recorded')) {
            return
        }
        request.setAttribute('audit.recorded', true)

        long startedAt = request.getAttribute('audit.startNanos') as long
        double elapsedMs = (System.nanoTime() - startedAt) / 1_000_000d

        try {
            auditRecorder.record(
                requestId: request.getAttribute('audit.requestId') as String,
                startedAt: request.getAttribute('audit.startedAt'),
                method: request.method,
                path: request.requestURI,
                status: response.status,
                elapsedMs: elapsedMs,
                principal: request.userPrincipal?.name,
                error: failure?.class?.name
            )
        } catch (Exception recordingFailure) {
            log.warn('Request audit recording failed for requestId={}',
                request.getAttribute('audit.requestId'))
        }
    }
}

before() stores the start value and request ID on the current request, then returns true so the action may proceed. afterView() records successful requests after view processing, while after(Throwable failure) covers the exceptional path and returns false so normal Grails error handling can take over. The recorded guard prevents two callbacks from publishing the same event.

Returning true from before() matters because false stops the action, which suits an authorisation rule but not passive timing. The request object belongs to one servlet call, so its attributes remain isolated between concurrent users. This makes the interceptor safer than keeping a start time in a singleton field, a mistake that would mix timings under load. Use after() instead of afterView() when only controller execution should count, and remember that neither approach measures the time spent transferring bytes across the internet.

Recording useful audit context

A useful event should carry the request ID, HTTP method, normalised route, status, duration, timestamp, authenticated principal when available, and failure type. Use a route template such as /orders/:orderId instead of a raw URI containing one million order identifiers. Raw paths create high-cardinality metric labels; the original ID can remain in a protected log field when investigators genuinely need it.

Keep the audit event small and avoid query strings, request bodies, access tokens, session cookies, and personal details unless a documented compliance case requires them. Store the event timestamp in UTC while retaining the application time zone for reporting. For a relational audit table, manage schema changes with the Liquibase migration guide; it shows how to version a Grails database alongside application code.

Handling failures and edge cases

Failures need the same care as successful requests. A database timeout, a missing domain object, or a rejected binding may produce different HTTP statuses, and each reveals a different kind of operational risk. Record the exception class and a safe error code, but let the normal exception mechanism render the response. Keep stack traces and sensitive messages out of routine timing logs, and make audit-recorder failures non-fatal so a logging outage cannot damage the application response.

An interceptor does not see everything. Requests rejected by a servlet filter, security plugin, reverse proxy, or front-end content delivery network may never reach the controller. Static assets and some error pages also sit outside its scope. Compare interceptor totals with proxy or application performance monitoring data before claiming complete coverage; the difference can itself identify an important blind spot.

Account for redirects, streaming responses, and unusually large payloads. A fast controller can still produce a slow response when a view serialises a huge collection. Test normal, failed, and cancelled requests in a Grails integration test, then verify that one logical request produces exactly one audit event. That invariant keeps the dataset trustworthy and prevents duplicate timings from distorting averages.

Following asynchronous and distributed work

Interceptor timing covers server-side request processing, not work that continues after the response. CompletableFuture, @Async, message consumers, and queued jobs need their own duration fields. If a controller starts background work and returns, label the controller event as accepted rather than complete, and let the worker record queue wait and execution time separately.

Propagate the request ID through headers, messages, and logging context so a slow payment provider can be linked to the Grails transaction that called it. Record upstream connect, read, and total-call durations where possible. On several application nodes, keep elapsed calculations local with a monotonic clock; use UTC timestamps and trace identifiers to assemble the distributed story without pretending every machine has perfectly synchronised time.

Preparing metrics for production

Operational telemetry should preserve detail while presenting a manageable overview. Emit one structured event per request, then aggregate latency histograms by normalised route and status. Dashboards should show p50, p95, and p99 values, error rates, and throughput. Averages alone hide tail latency, which is often what Australian customers notice when a mobile connection drops during checkout.

Set alerts from service-level objectives and sustained changes rather than a single slow request. A useful warning might trigger when the p95 for order creation exceeds its target for five minutes in the ap-southeast-2 region. Keep raw events in a time-indexed store for investigation and retain summaries for longer. Before selecting infrastructure, compare the practical hosting checks in Mashaleilm deployment notes with load-test results from the actual application.

Protect audit data as carefully as application logs. Apply access controls, define retention, and avoid putting credentials in URLs. Sampling can reduce volume, but retain all errors and a representative share of slow requests. Document the sampling rate so a sudden drop in traffic is not mistaken for an outage or a disabled interceptor.

Fitting the audit into Australian operations

Australian deployments add practical constraints that are easy to overlook. Teams in Sydney and Melbourne commonly place application nodes in nearby cloud regions, yet users in Brisbane, Perth, and Adelaide still cross long distances. Network paths vary by internet service provider, so compare regional latency and packet loss rather than using a single office ping as a proxy for customer experience.

Daylight-saving rules also split the country. Sydney, Melbourne, Canberra, and Hobart move between AEST and AEDT, while Brisbane, Perth, and Adelaide do not change their clocks. Store audit timestamps in UTC and display them in Australian Eastern Time when operations teams coordinate incidents. Daylight-saving boundaries also change day-length reports, so do not aggregate them by a naive local hour.

The Australian market rewards careful capacity planning around GST-inclusive AUD pricing, Christmas, the end of the financial year, and major online sale periods. Local support hours mean an alert can arrive when the responsible team is asleep, so route it to an on-call schedule with an Australian follow-up workflow. Privacy reviews should account for the Australian Privacy Principles and contractual data-residency requirements. Support notes from Australian offices often describe the symptom as “lagging” or “hanging”; put that wording alongside precise latency labels in the runbook so shared language still leads to measurable evidence.

Longer case studies and related framework lessons in the Grails Example magazine can help teams connect request auditing with database versioning, testing, packaging, and deployment practices.

Start with one controller representing an important customer journey, such as checkout or login. Capture the request ID, method, normalised route, status, and elapsed time; send events to structured logs first; and compare the results with an existing performance tool. Once the numbers make sense, add controlled persistence, failure handling, dashboards, and a retention policy before widening the scope.

Implement the interceptor in a small branch, test successful and failed actions, and have a teammate review the event fields and privacy choices. Then publish the verified pattern for the team and build the first operational dashboard from real traffic rather than assumptions.