Skip to content

Layer observability

A slow request answers 200 in 480ms, and the access log only shows the total wall-clock time. You still do not know whether the latency came from the controller, the service business rules, or the repository queries. This recipe shows how to measure each architectural layer with @timed and @instrument_layer, correlate every JSON log line with trace_id and span_id, and emit a per-layer layers summary directly on the AccessLogMiddleware record — opt-in, with include_layer_timings=True (the default is False).

Installation

No extra is required. @timed, @instrument_layer, the layers summary in AccessLogMiddleware (with include_layer_timings=True), and JSONFormatter all ship in the base package. When the [otel] extra is installed (uv add "tempest-fastapi-sdk[otel]"), every timed call automatically opens a child OpenTelemetry span and JSONFormatter attaches lowercase hex trace_id and span_id.

Time a single function or method with @timed

Use @timed when you want to measure a specific sync or async operation and emit a structured log record carrying layer, op, duration_ms, and outcome ("ok" or "error").

import asyncio
import logging

from tempest_fastapi_sdk import configure_logging, timed

configure_logging(level="INFO", file_output=False)


@timed("service", op="calculate_discount")
def calculate_discount(subtotal_cents: int, pct: float) -> int:
    """Compute the discount amount in cents."""
    return int(subtotal_cents * pct)


@timed("repository", op="fetch_order_items", threshold_ms=0.0)
async def fetch_order_items(order_id: str) -> list[str]:
    """Fetch the items belonging to an order."""
    await asyncio.sleep(0.01)
    return [f"{order_id}-item-1"]


async def main() -> None:
    """Run sync and async functions decorated with @timed."""
    discount: int = calculate_discount(10_000, 0.1)
    items: list[str] = await fetch_order_items("ord-42")
    logging.getLogger("demo").info(
        "order ready",
        extra={"discount": discount, "count": len(items)},
    )


asyncio.run(main())

The decorator preserves the wrapped callable's exact static type (mypy keeps seeing int for calculate_discount and list[str] for fetch_order_items). By default, records are emitted to the tempest.timing logger (DEFAULT_TIMING_LOGGER), which propagates to the root logger configured by configure_logging.

Filter fast calls with threshold_ms

Use threshold_ms to log only slow operations in production without drowning your log stream. Failing calls are always logged at error_level (default logging.ERROR) even when they fail below the threshold — errors are never silently dropped.

import logging

from tempest_fastapi_sdk import timed


@timed(
    "external",
    op="charge_gateway",
    threshold_ms=100.0,
    level=logging.WARNING,
    error_level=logging.ERROR,
)
async def charge_gateway(order_id: str) -> str:
    """Charge an order against an external payment gateway."""
    return f"tx-{order_id}"

Per-request aggregation stays accurate with threshold_ms

Even when a fast individual call stays below threshold_ms and skips emitting its own tempest.timing line, its duration is still added to the active request accumulator. The layers summary on AccessLogMiddleware (with include_layer_timings=True) still reflects the true time spent in each layer.

Instrument whole classes with @instrument_layer

Use @instrument_layer on BaseController, BaseService, BaseRepository subclasses or plain classes when you want to time every public method without decorating each one by hand.

from fastapi import FastAPI
from fastapi.testclient import TestClient

from tempest_fastapi_sdk import (
    AccessLogMiddleware,
    RequestIDMiddleware,
    configure_logging,
    instrument_layer,
    timed,
)

configure_logging(level="INFO", file_output=False)


@instrument_layer("repository")
class OrderRepository:
    """Data access layer for orders."""

    async def fetch_items(self, order_id: str) -> list[str]:
        """Return the items for an order."""
        return [f"{order_id}-item-1"]


@instrument_layer("service")
class OrderService:
    """Business logic for orders."""

    def __init__(self, repo: OrderRepository) -> None:
        """Initialize the service with its injected repository."""
        self.repo: OrderRepository = repo

    async def get_summary(self, order_id: str) -> dict[str, object]:
        """Build an order summary."""
        items: list[str] = await self.repo.fetch_items(order_id)
        return {"order_id": order_id, "items": items}

    @timed("service", op="recalculate_tax", threshold_ms=50.0)
    async def recalculate_tax(self, order_id: str) -> float:
        """Explicit per-method @timed override inside an instrumented class."""
        return 0.15


@instrument_layer("controller")
class OrderController:
    """Orchestration between router and service."""

    def __init__(self, service: OrderService) -> None:
        """Initialize the controller with its injected service."""
        self.service: OrderService = service

    async def show(self, order_id: str) -> dict[str, object]:
        """Delegate lookup to the service."""
        return await self.service.get_summary(order_id)


app: FastAPI = FastAPI()
controller: OrderController = OrderController(OrderService(OrderRepository()))


@app.get("/orders/{order_id}")
async def get_order(order_id: str) -> dict[str, object]:
    """Order lookup endpoint."""
    return await controller.show(order_id)


app.add_middleware(AccessLogMiddleware, include_layer_timings=True)
app.add_middleware(RequestIDMiddleware)

with TestClient(app) as client:
    response = client.get("/orders/ord-42", headers={"X-Request-ID": "req-demo-1"})
    print(response.status_code, response.json())

What @instrument_layer guarantees at runtime and under static type checkers:

  • Inherited CRUD methods carry the subclass name. On class UserService(BaseService[UserRepository, UserResponseSchema]), inherited methods (get_by_id, list, paginate, update, delete) are logged as UserService.get_by_id without mutating BaseService.
  • Async public methods by default. Lightweight sync helpers such as BaseRepository.map_to_response and context-manager factories like transaction() are skipped by default; pass include_sync=True to include sync methods and exclude= to skip specific names.
  • No double-wrapping. Methods already decorated with @timed (like recalculate_tax above) keep their explicit configuration.
  • Descriptors and private members preserved. Private (_...) methods, dunders, @property, and generator functions are left untouched; @classmethod and @staticmethod stay descriptors.

Per-request layers summary in AccessLogMiddleware

With include_layer_timings=True, AccessLogMiddleware binds a per-request ContextVar accumulator and resets it in finally, even on unhandled exceptions (500). Whenever at least one layer was timed during the request, the access log line gains a layers mapping:

{"timestamp": "2026-12-02T21:30:03.188399Z", "level": "INFO", "logger": "tempest.access", "message": "GET /orders/ord-42 200 1.4ms", "request_id": "req-demo-1", "http_method": "GET", "http_path": "/orders/ord-42", "http_query": "", "http_status": 200, "duration_ms": 1.399, "client_ip": "testclient", "layers": {"repository_ms": 0.02, "service_ms": 0.146, "controller_ms": 0.23}}

Routes where no @timed or @instrument_layer ran omit layers, keeping existing access-log payloads and tests unchanged. The default is include_layer_timings=False: without the opt-in, @timed and @instrument_layer still emit their own tempest.timing lines, but the access log line carries no layers.

OpenTelemetry correlation (trace_id and span_id)

When the [otel] extra is installed and a valid recording span is active (for example via setup_tracing), two things happen automatically:

  1. Each @timed / @instrument_layer call opens a child span named "<layer>.<op>" with attributes tempest.layer and tempest.op, recording the exception and setting status ERROR on failure.
  2. JSONFormatter checks sys.modules["opentelemetry.trace"] and attaches lowercase hex trace_id (32 hex chars) and span_id (16 hex chars) to every JSON log line — including the tempest.timing records emitted right before each span closes.

Measured output with an active TracerProvider running the example above:

{"timestamp": "2026-12-02T21:30:03.187582Z", "level": "INFO", "logger": "tempest.timing", "message": "repository.OrderRepository.fetch_items ok 0.0ms", "request_id": "req-demo-1", "trace_id": "331c3256259206875241ee7ff44e1005", "span_id": "7091f43524868070", "layer": "repository", "op": "OrderRepository.fetch_items", "duration_ms": 0.02, "outcome": "ok"}
{"timestamp": "2026-12-02T21:30:03.187661Z", "level": "INFO", "logger": "tempest.timing", "message": "service.OrderService.get_summary ok 0.1ms", "request_id": "req-demo-1", "trace_id": "331c3256259206875241ee7ff44e1005", "span_id": "a8af6a7adc733bd2", "layer": "service", "op": "OrderService.get_summary", "duration_ms": 0.146, "outcome": "ok"}
{"timestamp": "2026-12-02T21:30:03.187696Z", "level": "INFO", "logger": "tempest.timing", "message": "controller.OrderController.show ok 0.2ms", "request_id": "req-demo-1", "trace_id": "331c3256259206875241ee7ff44e1005", "span_id": "e5c8e774f1f9be29", "layer": "controller", "op": "OrderController.show", "duration_ms": 0.23, "outcome": "ok"}

Without [otel] or outside an active recording span, JSONFormatter omits trace_id and span_id and never imports OpenTelemetry.

Accumulator outside HTTP (workers and tasks)

Use start_layer_timings, get_layer_timings, and clear_layer_timings in queue consumers or background tasks to collect the same per-layer breakdown outside AccessLogMiddleware:

import asyncio

from tempest_fastapi_sdk import (
    clear_layer_timings,
    get_layer_timings,
    start_layer_timings,
    timed,
)


@timed("worker", op="sync_catalog")
async def sync_catalog() -> None:
    """Simulate background work."""
    await asyncio.sleep(0.01)


async def run_job() -> dict[str, float] | None:
    """Run work inside a layer timing scope."""
    token = start_layer_timings()
    try:
        await sync_catalog()
        return get_layer_timings()
    finally:
        clear_layer_timings(token)


print(asyncio.run(run_job()))

See all signatures in the tempest_fastapi_sdk.core reference.

Recap

  • @timed("service", op=..., threshold_ms=...) times sync and async callables, emits structured fields (layer, op, duration_ms, outcome), always logs errors even below threshold_ms, and opens OpenTelemetry spans when [otel] is installed.
  • @instrument_layer("controller" | "service" | "repository") wraps public methods (async by default, including inherited BaseController, BaseService, and BaseRepository methods) while preserving descriptors, static types, and explicit @timed overrides.
  • JSONFormatter attaches trace_id (32 hex chars) and span_id (16 hex chars) whenever a valid recording OpenTelemetry span is active, and omits both with zero overhead otherwise.
  • AccessLogMiddleware(include_layer_timings=True) — opt-in, the default is False — emits layers: {"<layer>_ms": ...} whenever at least one layer was timed during the request (both on 200s and on 500s), and omits the key when none ran.