Наблюдаемость: трассировка, корреляция, метрики и алерты

Наблюдаемость: трассировка, корреляция, метрики и алерты

В синхронной системе отладка проста: запрос приходит, проходит через middleware, handler, service, repository - и ответ уходит. Один HTTP-запрос, одна горутина, один стектрейс. В event-driven системе одно действие пользователя может породить цепочку из десятка событий, обработанных разными подписчиками, возможно в разных сервисах, с задержкой в миллисекунды или минуты. Без специальных инструментов наблюдаемости вы будете искать причину бага, перебирая логи вручную.

Три столпа наблюдаемости (Three Pillars of Observability) - логи, метрики, трейсы - особенно критичны для event-driven архитектуры.

Correlation ID: связываем цепочку событий

Correlation ID - уникальный идентификатор, который генерируется при входящем запросе и передаётся через все события и подписчики. Он позволяет собрать все логи одного пользовательского действия в один trace.

Correlation ID путешествует через HTTP → Use-Case → Event → Subscriber; один grep собирает всю цепочку

Middleware для генерации correlation_id

// CorrelationMiddleware добавляет correlation_id в контекст запроса.
// Если клиент передал X-Correlation-ID - используем его,
// иначе генерируем новый.
func CorrelationMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        correlationID := r.Header.Get("X-Correlation-ID")
        if correlationID == "" {
            correlationID = ulid.Make().String()
        }

        // Сохраняем в контекст
        ctx := context.WithValue(r.Context(), correlationKey, correlationID)

        // Отдаём в заголовке ответа (удобно для отладки)
        w.Header().Set("X-Correlation-ID", correlationID)

        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// CorrelationFromCtx извлекает correlation_id из контекста.
func CorrelationFromCtx(ctx context.Context) string {
    if v, ok := ctx.Value(correlationKey).(string); ok {
        return v
    }
    return ""
}
<?php
// src/Infrastructure/Http/EventListener/CorrelationIdListener.php
declare(strict_types=1);

namespace App\Infrastructure\Http\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Uid\Ulid;

// Слушаем kernel.request и kernel.response: на входе кладём correlation_id
// в атрибуты запроса (если клиент не передал - генерируем), на выходе
// добавляем тот же id в заголовок ответа.
#[AsEventListener(event: KernelEvents::REQUEST, method: 'onRequest', priority: 256)]
#[AsEventListener(event: KernelEvents::RESPONSE, method: 'onResponse')]
final class CorrelationIdListener
{
    public const string ATTRIBUTE = 'correlation_id';
    public const string HEADER = 'X-Correlation-ID';

    public function onRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $correlationId = $request->headers->get(self::HEADER) ?? (string) new Ulid();
        $request->attributes->set(self::ATTRIBUTE, $correlationId);
    }

    public function onResponse(ResponseEvent $event): void
    {
        $correlationId = $event->getRequest()->attributes->get(self::ATTRIBUTE);
        if (is_string($correlationId)) {
            $event->getResponse()->headers->set(self::HEADER, $correlationId);
        }
    }
}

// src/Infrastructure/Logging/CorrelationIdProcessor.php
// Monolog processor: добавляет correlation_id в каждую запись лога.
final class CorrelationIdProcessor
{
    public function __construct(
        private readonly RequestStack $requestStack,
    ) {}

    public function __invoke(array $record): array
    {
        $request = $this->requestStack->getCurrentRequest();
        if ($request !== null) {
            $record['extra']['correlation_id'] = $request->attributes->get(CorrelationIdListener::ATTRIBUTE);
        }

        return $record;
    }
}
# infrastructure/http/correlation.py
import uuid
from contextvars import ContextVar
from typing import Callable, Iterable

WSGIApp = Callable[[dict, Callable], Iterable[bytes]]

# Аналог значения в context.Context: contextvars живут в пределах запроса
# и в потоках, и в asyncio-задачах.
_correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")


class CorrelationMiddleware:
    """Добавляет correlation_id в контекст запроса.

    Если клиент передал X-Correlation-ID - используем его,
    иначе генерируем новый.
    Фреймворк-независимый WSGI-вариант: в FastAPI/Starlette это BaseHTTPMiddleware,
    в Django - класс middleware с __call__(request).
    """

    def __init__(self, app: WSGIApp) -> None:
        self._app = app

    def __call__(self, environ: dict, start_response: Callable) -> Iterable[bytes]:
        correlation_id = environ.get("HTTP_X_CORRELATION_ID", "")
        if not correlation_id:
            # В Go здесь ULID; в стандартной библиотеке его нет - uuid4 или пакет python-ulid
            correlation_id = str(uuid.uuid4())

        # Сохраняем в контекст
        token = _correlation_id.set(correlation_id)

        # Отдаём в заголовке ответа (удобно для отладки)
        def start_response_with_header(status: str, headers: list, exc_info=None):
            headers = [*headers, ("X-Correlation-ID", correlation_id)]
            return start_response(status, headers, exc_info)

        try:
            return self._app(environ, start_response_with_header)
        finally:
            _correlation_id.reset(token)


def correlation_from_ctx() -> str:
    """Извлекает correlation_id из контекста."""
    return _correlation_id.get()

Передача correlation_id в событие

// PublishEvent включает correlation_id в payload события.
func (p *EventPublisher) PublishEvent(ctx context.Context, eventType string, data any) error {
    envelope := EventEnvelope{
        EventID:       ulid.Make().String(),
        Type:          eventType,
        CorrelationID: CorrelationFromCtx(ctx),
        OccurredAt:    time.Now().UTC(),
        Data:          data,
    }

    payload, err := json.Marshal(envelope)
    if err != nil {
        return fmt.Errorf("marshal event: %w", err)
    }

    return p.broker.Publish(ctx, eventType, payload)
}

// EventEnvelope - конверт события с метаданными.
type EventEnvelope struct {
    EventID       string    `json:"event_id"`
    Type          string    `json:"type"`
    CorrelationID string    `json:"correlation_id"`
    OccurredAt    time.Time `json:"occurred_at"`
    Data          any       `json:"data"`
}
<?php
// src/Infrastructure/Messaging/EventEnvelope.php
declare(strict_types=1);

namespace App\Infrastructure\Messaging;

// EventEnvelope - конверт события с метаданными.
final readonly class EventEnvelope
{
    public function __construct(
        public string $eventId,
        public string $type,
        public string $correlationId,
        public DateTimeImmutable $occurredAt,
        public array $data,
    ) {}
}

// src/Infrastructure/Messaging/EventPublisher.php
namespace App\Infrastructure\Messaging;

use App\Infrastructure\Http\EventListener\CorrelationIdListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Uid\Ulid;
use DateTimeImmutable;

final class EventPublisher
{
    public function __construct(
        private readonly BrokerInterface $broker,
        private readonly RequestStack $requestStack,
    ) {}

    // publishEvent включает correlation_id в payload события.
    public function publishEvent(string $eventType, array $data): void
    {
        $envelope = new EventEnvelope(
            eventId: (string) new Ulid(),
            type: $eventType,
            correlationId: $this->correlationId(),
            occurredAt: new DateTimeImmutable(),
            data: $data,
        );

        $payload = json_encode($envelope, JSON_THROW_ON_ERROR);
        $this->broker->publish($eventType, $payload);
    }

    private function correlationId(): string
    {
        $request = $this->requestStack->getCurrentRequest();

        return $request?->attributes->get(CorrelationIdListener::ATTRIBUTE) ?? '';
    }
}

В Symfony Messenger вместо собственного EventEnvelope обычно используется Symfony\Component\Messenger\Envelope + stamp (например, CorrelationIdStamp), а middleware на bus добавляет stamp в каждое исходящее сообщение и копирует его на дочерние сообщения внутри handler-а.

# infrastructure/messaging/event_publisher.py
import json
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from typing import Any, Protocol


class Broker(Protocol):
    def publish(self, event_type: str, payload: bytes) -> None: ...


@dataclass(frozen=True, slots=True)
class EventEnvelope:
    """Конверт события с метаданными."""

    event_id: str
    event_type: str
    correlation_id: str
    occurred_at: datetime
    data: Any


class EventPublisher:
    def __init__(self, broker: Broker) -> None:
        self._broker = broker

    def publish_event(self, event_type: str, data: Any) -> None:
        """Включает correlation_id в payload события."""
        envelope = EventEnvelope(
            # В Go здесь ULID: он сортируется по времени создания. В stdlib
            # Python ULID нет - пакет python-ulid (str(ULID())) или UUIDv7
            # (uuid.uuid7() в 3.14+, раньше - пакет uuid6). uuid4 случаен,
            # порядок по нему не восстановить
            event_id=str(uuid.uuid4()),
            event_type=event_type,
            correlation_id=correlation_from_ctx(),
            occurred_at=datetime.now(timezone.utc),
            data=data,
        )

        # json.dumps не умеет datetime - сериализуем через default
        payload = json.dumps(asdict(envelope), default=_json_default).encode()

        self._broker.publish(event_type, payload)


def _json_default(value: object) -> str:
    if isinstance(value, datetime):
        return value.isoformat()
    raise TypeError(f"not JSON serializable: {type(value).__name__}")

Подписчик, получив событие, извлекает correlation_id и кладёт его в свой контекст. Все логи этого подписчика будут содержать тот же ID. В Kibana/Grafana Loki достаточно отфильтровать по correlation_id, чтобы увидеть всю цепочку.

Structured Logging с slog

Каждый подписчик логирует обработку событий структурированно. Не printf/echo, а структурный logger с атрибутами:

// HandleEvent обрабатывает событие с полным структурированным логированием.
func (h *AchievementHandler) HandleEvent(ctx context.Context, envelope EventEnvelope) error {
    logger := slog.With(
        slog.String("correlation_id", envelope.CorrelationID),
        slog.String("event_id", envelope.EventID),
        slog.String("event_type", envelope.Type),
        slog.String("handler", "achievement_checker"),
    )

    start := time.Now()
    logger.InfoContext(ctx, "event processing started")

    err := h.process(ctx, envelope)

    duration := time.Since(start)
    if err != nil {
        logger.ErrorContext(ctx, "event processing failed",
            slog.String("err", err.Error()),
            slog.Duration("duration", duration),
        )
        return err
    }

    logger.InfoContext(ctx, "event processing completed",
        slog.Duration("duration", duration),
    )
    return nil
}
<?php
// src/Application/EventHandler/AchievementHandler.php
declare(strict_types=1);

namespace App\Application\EventHandler;

use App\Infrastructure\Messaging\EventEnvelope;
use Psr\Log\LoggerInterface;
use Throwable;

// HandleEvent обрабатывает событие с полным структурированным логированием.
// В Symfony Monolog настраивается с JsonFormatter - каждая запись уходит
// как одна JSON-строка с атрибутами в context (для ELK/Loki).
final class AchievementHandler
{
    public function __construct(
        private readonly LoggerInterface $logger,
        private readonly AchievementProcessor $processor,
    ) {}

    public function handleEvent(EventEnvelope $envelope): void
    {
        $ctx = [
            'correlation_id' => $envelope->correlationId,
            'event_id' => $envelope->eventId,
            'event_type' => $envelope->type,
            'handler' => 'achievement_checker',
        ];

        $start = microtime(true);
        $this->logger->info('event processing started', $ctx);

        try {
            $this->processor->process($envelope);
        } catch (Throwable $e) {
            $this->logger->error('event processing failed', $ctx + [
                'err' => $e->getMessage(),
                'duration_ms' => (int) round((microtime(true) - $start) * 1000),
            ]);
            throw $e;
        }

        $this->logger->info('event processing completed', $ctx + [
            'duration_ms' => (int) round((microtime(true) - $start) * 1000),
        ]);
    }
}

В PHP нет прямого аналога slog - структурированный JSON-лог собирается через Monolog c JsonFormatter (или LogstashFormatter) + processor-ы (PsrLogMessageProcessor, кастомный CorrelationIdProcessor). Атрибуты передаются через массив context, а ближайший аналог slog.With() для долгоживущего набора полей - processor, добавляющий поля в extra каждой записи (как CorrelationIdProcessor). Logger::withName() только клонирует логгер с другим именем канала и полей не добавляет.

# application/event_handler/achievement_handler.py
import logging
import time

# JSON-вывод (для ELK/Loki) настраивается на уровне logging: свой Formatter,
# который сериализует record.__dict__, или библиотека structlog.
log = logging.getLogger(__name__)


class AchievementHandler:
    def handle_event(self, envelope: EventEnvelope) -> None:
        """Обрабатывает событие с полным структурированным логированием."""
        # Аналог slog.With: набор полей, который уходит в extra каждой записи ниже.
        # (LoggerAdapter до 3.13 затирает extra вызова своим - поэтому словарь.)
        fields = {
            "correlation_id": envelope.correlation_id,
            "event_id": envelope.event_id,
            "event_type": envelope.event_type,
            "handler": "achievement_checker",
        }

        start = time.perf_counter()
        log.info("event processing started", extra=fields)

        try:
            self._process(envelope)
        except Exception as err:
            duration = time.perf_counter() - start
            log.error(
                "event processing failed",
                extra={**fields, "err": str(err), "duration_s": duration},
            )
            raise

        duration = time.perf_counter() - start
        log.info("event processing completed", extra={**fields, "duration_s": duration})

Результат в JSON (для ELK/Loki). slog.JSONHandler пишет slog.Duration целым числом наносекунд, строку вида 2.341ms даёт только TextHandler:

{
  "time": "2026-05-03T14:22:01Z",
  "level": "INFO",
  "msg": "event processing completed",
  "correlation_id": "01JXYZ...",
  "event_id": "01JABC...",
  "event_type": "lesson.completed",
  "handler": "achievement_checker",
  "duration": 2341000
}

Теперь по correlation_id в Kibana вы найдёте: HTTP-запрос -> use-case -> outbox insert -> poller publish -> subscriber receive -> subscriber process. Вся цепочка.

Метрики с Prometheus

Числовые метрики показывают здоровье системы в реальном времени. Для event-driven системы критичны:

import "github.com/prometheus/client_golang/prometheus"

var (
    // Счётчик опубликованных событий
    eventsPublished = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "events_published_total",
            Help: "Total number of events published to broker",
        },
        []string{"event_type"},
    )

    // Счётчик обработанных событий
    eventsProcessed = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "events_processed_total",
            Help: "Total number of events processed by subscribers",
        },
        []string{"event_type", "handler", "status"}, // status: success, error
    )

    // Гистограмма времени обработки
    processingDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "event_processing_duration_seconds",
            Help:    "Time spent processing an event",
            Buckets: []float64{0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5},
        },
        []string{"event_type", "handler"},
    )

    // Gauge: количество событий в outbox, ожидающих отправки
    outboxPending = prometheus.NewGauge(
        prometheus.GaugeOpts{
            Name: "outbox_pending_events",
            Help: "Number of events in outbox waiting to be published",
        },
    )
)

func init() {
    prometheus.MustRegister(eventsPublished, eventsProcessed, processingDuration, outboxPending)
}
<?php
// src/Infrastructure/Metrics/EventMetrics.php
declare(strict_types=1);

namespace App\Infrastructure\Metrics;

use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
use Prometheus\Histogram;

// Регистрация метрик через promphp/prometheus_client_php
// (CollectorRegistry, Counter, Gauge, Histogram).
final class EventMetrics
{
    private readonly Counter $eventsPublished;
    private readonly Counter $eventsProcessed;
    private readonly Histogram $processingDuration;
    private readonly Gauge $outboxPending;

    public function __construct(CollectorRegistry $registry)
    {
        // Счётчик опубликованных событий
        $this->eventsPublished = $registry->getOrRegisterCounter(
            'app',
            'events_published_total',
            'Total number of events published to broker',
            ['event_type'],
        );

        // Счётчик обработанных событий (status: success, error)
        $this->eventsProcessed = $registry->getOrRegisterCounter(
            'app',
            'events_processed_total',
            'Total number of events processed by subscribers',
            ['event_type', 'handler', 'status'],
        );

        // Гистограмма времени обработки (секунды)
        $this->processingDuration = $registry->getOrRegisterHistogram(
            'app',
            'event_processing_duration_seconds',
            'Time spent processing an event',
            ['event_type', 'handler'],
            [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5],
        );

        // Gauge: количество событий в outbox, ожидающих отправки
        $this->outboxPending = $registry->getOrRegisterGauge(
            'app',
            'outbox_pending_events',
            'Number of events in outbox waiting to be published',
        );
    }

    public function publishedInc(string $eventType): void
    {
        $this->eventsPublished->inc([$eventType]);
    }

    public function processedInc(string $eventType, string $handler, string $status): void
    {
        $this->eventsProcessed->inc([$eventType, $handler, $status]);
    }

    public function observeDuration(string $eventType, string $handler, float $seconds): void
    {
        $this->processingDuration->observe($seconds, [$eventType, $handler]);
    }

    public function setOutboxPending(int $count): void
    {
        $this->outboxPending->set($count);
    }
}
# infrastructure/metrics/event_metrics.py
from prometheus_client import Counter, Gauge, Histogram

# prometheus_client регистрирует метрики в глобальном REGISTRY при создании -
# отдельного MustRegister не нужно. Отдача: start_http_server(9100)
# или make_wsgi_app() на /metrics.

# Счётчик опубликованных событий
events_published = Counter(
    "events_published_total",
    "Total number of events published to broker",
    ["event_type"],
)

# Счётчик обработанных событий
events_processed = Counter(
    "events_processed_total",
    "Total number of events processed by subscribers",
    ["event_type", "handler", "status"],  # status: success, error
)

# Гистограмма времени обработки
processing_duration = Histogram(
    "event_processing_duration_seconds",
    "Time spent processing an event",
    ["event_type", "handler"],
    buckets=(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5),
)

# Gauge: количество событий в outbox, ожидающих отправки
outbox_pending = Gauge(
    "outbox_pending_events",
    "Number of events in outbox waiting to be published",
)

Использование в обработчике:

// InstrumentedHandler оборачивает обработчик и записывает метрики.
func InstrumentedHandler(handler, eventType string, fn func(ctx context.Context) error) func(ctx context.Context) error {
    return func(ctx context.Context) error {
        start := time.Now()

        err := fn(ctx)

        duration := time.Since(start).Seconds()
        status := "success"
        if err != nil {
            status = "error"
        }

        eventsProcessed.WithLabelValues(eventType, handler, status).Inc()
        processingDuration.WithLabelValues(eventType, handler).Observe(duration)

        return err
    }
}
<?php
// src/Infrastructure/Messaging/InstrumentedHandler.php
declare(strict_types=1);

namespace App\Infrastructure\Messaging;

use App\Infrastructure\Metrics\EventMetrics;
use Throwable;

// InstrumentedHandler оборачивает обработчик и записывает метрики.
final class InstrumentedHandler
{
    public function __construct(
        private readonly EventMetrics $metrics,
        private readonly string $handler,
        private readonly string $eventType,
        /** @var callable(EventEnvelope): void */
        private $inner,
    ) {}

    public function __invoke(EventEnvelope $envelope): void
    {
        $start = microtime(true);
        $status = 'success';

        try {
            ($this->inner)($envelope);
        } catch (Throwable $e) {
            $status = 'error';
            throw $e;
        } finally {
            $duration = microtime(true) - $start;
            $this->metrics->processedInc($this->eventType, $this->handler, $status);
            $this->metrics->observeDuration($this->eventType, $this->handler, $duration);
        }
    }
}
# infrastructure/messaging/instrumented_handler.py
import time
from typing import Callable

from infrastructure.metrics.event_metrics import events_processed, processing_duration


def instrumented_handler(
    handler: str, event_type: str, fn: Callable[[], None],
) -> Callable[[], None]:
    """Оборачивает обработчик и записывает метрики."""
    def wrapped() -> None:
        start = time.perf_counter()
        status = "success"

        try:
            fn()
        except Exception:
            status = "error"
            raise
        finally:
            duration = time.perf_counter() - start
            events_processed.labels(event_type, handler, status).inc()
            processing_duration.labels(event_type, handler).observe(duration)

    return wrapped

Distributed Tracing: OpenTelemetry

Метрики показывают агрегированную картину. Трейсы показывают конкретный путь конкретного события. OpenTelemetry позволяет создать span на каждом этапе: publish -> broker -> consume -> process.

Пока достаточно знать: trace - весь путь одного запроса через систему, span - один его этап с началом, длительностью и атрибутами; у всех span-ов одного пути общий trace_id. OpenTelemetry (OTel) - стандартная библиотека, которая создаёт span-ы и передаёт контекст трейса дальше (в HTTP-заголовках или заголовках сообщения в брокере), а Jaeger/Tempo - хранилища, где трейс смотрят как диаграмму. Подробно - в уроке Distributed tracing.

import (
    "context"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
    "go.opentelemetry.io/otel/codes"
    "go.opentelemetry.io/otel/propagation"
    "go.opentelemetry.io/otel/trace"
)

// При старте приложения: без этого propagator по умолчанию ничего не делает.
//   otel.SetTextMapPropagator(propagation.TraceContext{})

var tracer = otel.Tracer("event-processing")

// PublishWithTrace создаёт span при публикации события.
func (p *Publisher) PublishWithTrace(ctx context.Context, eventType string, payload []byte) error {
    ctx, span := tracer.Start(ctx, "event.publish",
        trace.WithSpanKind(trace.SpanKindProducer),
        trace.WithAttributes(
            attribute.String("event.type", eventType),
        ),
    )
    defer span.End()

    // Inject: кладём traceparent текущего span-а в заголовки сообщения
    // (для Kafka - в message headers, для NATS - в message metadata).
    // Без этого consumer начнёт новый trace, и цепочка оборвётся.
    headers := propagation.MapCarrier{}
    otel.GetTextMapPropagator().Inject(ctx, headers)

    err := p.broker.Publish(ctx, eventType, payload, headers)
    if err != nil {
        span.SetStatus(codes.Error, err.Error())
    }
    return err
}

// ConsumeWithTrace создаёт span при обработке события.
func (s *Subscriber) ConsumeWithTrace(ctx context.Context, msg Message) error {
    // Extract: достаём traceparent из заголовков (msg.Headers - map[string]string),
    // чтобы span обработки стал дочерним к span-у публикации
    ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(msg.Headers))
    ctx, span := tracer.Start(ctx, "event.process",
        trace.WithSpanKind(trace.SpanKindConsumer),
        trace.WithAttributes(
            attribute.String("event.type", msg.Type),
            attribute.String("event.id", msg.EventID),
        ),
    )
    defer span.End()

    err := s.handler(ctx, msg)
    if err != nil {
        span.SetStatus(codes.Error, err.Error())
    }
    return err
}
<?php
// src/Infrastructure/Tracing/TracedPublisher.php
declare(strict_types=1);

namespace App\Infrastructure\Tracing;

use App\Infrastructure\Messaging\BrokerInterface;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\Context\Context;
use Throwable;

// TracedPublisher создаёт span при публикации события.
// Trace context инжектится в headers сообщения (TextMapPropagator)
// и извлекается в consumer-е - так получается единый trace publisher -> consumer.
final class TracedPublisher
{
    public function __construct(
        private readonly BrokerInterface $broker,
    ) {}

    public function publishWithTrace(string $eventType, string $payload, array $headers = []): void
    {
        $tracer = Globals::tracerProvider()->getTracer('event-processing');
        $span = $tracer->spanBuilder('event.publish')
 ->setSpanKind(SpanKind::KIND_PRODUCER)
 ->setAttribute('event.type', $eventType)
 ->startSpan();

        $scope = $span->activate();
        try {
            // Inject trace context в headers сообщения
            Globals::propagator()->inject($headers);
            $this->broker->publish($eventType, $payload, $headers);
        } catch (Throwable $e) {
            $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }
}

// src/Infrastructure/Tracing/TracedSubscriber.php
namespace App\Infrastructure\Tracing;

// TracedSubscriber создаёт span при обработке события.
final class TracedSubscriber
{
    /**
     * @param  callable(string): void  $handler
     */
    public function __construct(
        private $handler,
    ) {}

    public function consumeWithTrace(string $eventType, string $eventId, array $headers, string $body): void
    {
        // Extract trace context из headers сообщения
        $parent = Globals::propagator()->extract($headers);

        $tracer = Globals::tracerProvider()->getTracer('event-processing');
        $span = $tracer->spanBuilder('event.process')
 ->setParent($parent)
 ->setSpanKind(SpanKind::KIND_CONSUMER)
 ->setAttribute('event.type', $eventType)
 ->setAttribute('event.id', $eventId)
 ->startSpan();

        $scope = $span->activate();
        try {
            ($this->handler)($body);
        } catch (Throwable $e) {
            $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }
}

В Symfony Messenger пакет open-telemetry/sdk + middleware на bus делают то же автоматически: на отправке кладут traceparent в stamp, на consume извлекают и стартуют дочерний span. Ручной inject/extract обычно нужен только при работе с «голым» Kafka/AMQP-клиентом.

# infrastructure/tracing/traced.py
from typing import Callable

from opentelemetry import trace
from opentelemetry.propagate import extract, inject
from opentelemetry.trace import SpanKind

tracer = trace.get_tracer("event-processing")


class Publisher:
    def __init__(self, broker: Broker) -> None:
        self._broker = broker

    def publish_with_trace(self, event_type: str, payload: bytes) -> None:
        """Создаёт span при публикации события."""
        # start_as_current_span закрывает span при выходе из with, а если
        # вылетело исключение - сам записывает его в span и ставит статус
        # ERROR (record_exception и set_status_on_exception по умолчанию True).
        # Поэтому try/except с span.set_status здесь не нужен - исключение
        # просто летит дальше
        with tracer.start_as_current_span(
            "event.publish",
            kind=SpanKind.PRODUCER,
            attributes={"event.type": event_type},
        ):
            # Inject: кладём traceparent текущего span-а в заголовки сообщения
            # (для Kafka - message headers, для NATS - message metadata).
            # Без этого consumer начнёт новый trace, и цепочка оборвётся.
            headers: dict[str, str] = {}
            inject(headers)
            self._broker.publish(event_type, payload, headers)


class Subscriber:
    def __init__(self, handler: Callable[[Message], None]) -> None:
        self._handler = handler

    def consume_with_trace(self, msg: Message) -> None:
        """Создаёт span при обработке события."""
        # Extract: достаём traceparent из заголовков (msg.headers - dict[str, str]),
        # чтобы span обработки стал дочерним к span-у публикации.
        # Статус ERROR при исключении span тоже поставит сам - см. выше
        parent_ctx = extract(msg.headers)
        with tracer.start_as_current_span(
            "event.process",
            context=parent_ctx,
            kind=SpanKind.CONSUMER,
            attributes={"event.type": msg.event_type, "event.id": msg.event_id},
        ):
            self._handler(msg)

В Jaeger/Tempo вы увидите единый trace: HTTP request -> publish (3ms) -> consume (1ms) -> process (45ms) -> achievement granted. С таймингами каждого этапа. По такому трейсу видно две вещи: какой этап тормозит всю цепочку (bottleneck) и какие ожидаемые span-ы так и не появились - значит, событие потерялось или подписчик не сработал.

На что настраивать алерты

Метрики бесполезны без алертов. Ключевые сигналы для event-driven системы:

Consumer lag - количество необработанных сообщений в очереди. Если lag растёт, consumers не справляются. Алерт: lag > 1000 в течение 5 минут. Для Kafka это метрика kafka-exporter kafka_consumergroup_lag: разница между последним offset в партиции и закоммиченным offset группы. Как снять этот показатель именно с Kafka - через kafka-consumer-groups, kafka-exporter и kprom - разобрано в уроке мониторинг Kafka.

Error rate - процент ошибок при обработке. Алерт: error rate > 5% за последние 10 минут.

Processing latency p99 - 99-й перцентиль времени обработки. Алерт: p99 > 5 секунд.

Outbox pending count - количество неотправленных событий в outbox. Если растёт - poller не работает или брокер недоступен. Алерт: возраст самой старой неотправленной записи (now() - min(created_at) WHERE published_at IS NULL) больше 5 минут. Абсолютное число pending ложно срабатывает при batch-импорте (см. типичные ошибки).

Dead Letter Queue - события, которые не удалось обработать после всех retry. Алерт: скорость поступления в DLQ выше N в минуту или возраст самого старого сообщения больше 30 минут. Для такого алерта рядом с events_processed_total и event_processing_duration_seconds заводят gauge с текущим размером DLQ (например, dead_letter_queue_size) и счётчик поступлений в неё. Сами события в DLQ разбирают ежедневно, но будить дежурного из-за единичного письма не нужно.

Dead Letter Queue: последний рубеж

Если событие не удалось обработать после N попыток, оно попадает в Dead Letter Queue (DLQ). DLQ - это не мусорка, а карантин. События в DLQ требуют ручного анализа: баг в коде, невалидные данные, недоступный внешний сервис. На уровне RabbitMQ DLQ настраивается аргументом x-dead-letter-exchange у основной очереди - пошаговая настройка dead-letter exchange, retry-очередей и разбор poison messages в уроке Idempotency + Dead Letter Queue.

// ProcessWithRetry обрабатывает событие с retry и отправкой в DLQ.
func (s *Subscriber) ProcessWithRetry(ctx context.Context, msg Message, maxRetries int) error {
    for attempt := 1; attempt <= maxRetries; attempt++ {
        err := s.handler(ctx, msg)
        if err == nil {
            return nil
        }

        slog.WarnContext(ctx, "event processing retry",
            slog.String("event_id", msg.EventID),
            slog.Int("attempt", attempt),
            slog.Int("max_retries", maxRetries),
            slog.String("err", err.Error()),
        )

        // Экспоненциальная пауза: 100, 200, 400 мс. После последней попытки
        // не ждём - сразу в DLQ. Отмена ctx прерывает ожидание.
        if attempt < maxRetries {
            select {
            case <-time.After(time.Duration(1<<(attempt-1)) * 100 * time.Millisecond):
            case <-ctx.Done():
                return ctx.Err()
            }
        }
    }

    // Все попытки исчерпаны - отправляем в DLQ
    slog.ErrorContext(ctx, "event moved to DLQ",
        slog.String("event_id", msg.EventID),
        slog.String("event_type", msg.Type),
    )
    return s.dlq.Send(ctx, msg)
}
<?php
// src/Infrastructure/Messaging/ProcessWithRetry.php
declare(strict_types=1);

namespace App\Infrastructure\Messaging;

use Psr\Log\LoggerInterface;
use Throwable;

// ProcessWithRetry обрабатывает событие с retry и отправкой в DLQ.
final class ProcessWithRetry
{
    public function __construct(
        /** @var callable(Message): void */
        private $handler,
        private readonly DeadLetterQueue $dlq,
        private readonly LoggerInterface $logger,
        private readonly int $maxRetries = 3,
    ) {}

    public function process(Message $msg): void
    {
        for ($attempt = 1; $attempt <= $this->maxRetries; $attempt++) {
            try {
                ($this->handler)($msg);

                return;
            } catch (Throwable $e) {
                $this->logger->warning('event processing retry', [
                    'event_id' => $msg->eventId,
                    'attempt' => $attempt,
                    'max_retries' => $this->maxRetries,
                    'err' => $e->getMessage(),
                ]);

                // Exponential backoff (квадратичный, миллисекунды)
                usleep($attempt * $attempt * 100_000);
            }
        }

        // Все попытки исчерпаны - отправляем в DLQ
        $this->logger->error('event moved to DLQ', [
            'event_id' => $msg->eventId,
            'event_type' => $msg->type,
        ]);

        $this->dlq->send($msg);
    }
}

В Symfony Messenger вся retry-логика + DLQ делается декларативно: retry_strategy.max_retries, failure_transport - сообщение после исчерпания попыток автоматически уезжает в failure-транспорт (он же DLQ), а messenger:failed:show/messenger:failed:retry - консольные команды для разбора инцидентов.

# infrastructure/messaging/process_with_retry.py
import logging
import time
from typing import Callable, Protocol

log = logging.getLogger(__name__)


class DeadLetterQueue(Protocol):
    def send(self, msg: Message) -> None: ...


class Subscriber:
    def __init__(self, handler: Callable[[Message], None], dlq: DeadLetterQueue) -> None:
        self._handler = handler
        self._dlq = dlq

    def process_with_retry(self, msg: Message, max_retries: int) -> None:
        """Обрабатывает событие с retry и отправкой в DLQ."""
        for attempt in range(1, max_retries + 1):
            try:
                self._handler(msg)
                return
            except Exception as err:
                log.warning(
                    "event processing retry",
                    extra={
                        "event_id": msg.event_id,
                        "attempt": attempt,
                        "max_retries": max_retries,
                        "err": str(err),
                    },
                )

            # Exponential backoff
            time.sleep(attempt * attempt * 0.1)

        # Все попытки исчерпаны - отправляем в DLQ
        log.error(
            "event moved to DLQ",
            extra={"event_id": msg.event_id, "event_type": msg.event_type},
        )
        self._dlq.send(msg)

🚫 Без correlation_id отладка event-driven системы - как поиск иголки в стоге сена

Первое, что нужно сделать при переходе на event-driven архитектуру - добавить correlation_id в каждое событие и каждый лог. Без этого вы не сможете связать HTTP-запрос пользователя с цепочкой событий, которые он вызвал. Добавьте его до того, как система выйдет в production.

Типичные ошибки

  • correlation_id теряется при ре-публикации - subscriber обрабатывает событие A, генерирует событие B, кладёт новый correlation_id. Цепочка обрывается. Пробрасывай тот же correlation_id из входящего события в исходящие - единый «trace» через всю цепочку.
  • Алёрт на «есть события в DLQ» - каждое случайное падение consumer-а будит дежурного. Алёртить не на сам факт, а на rate (≥ N в минуту) или age старейшего письма (висит > 30 мин - действительно проблема).
  • Метрика events_processed_total без label-а handler - все subscriber-ы сливаются в один счётчик, не понять, какой именно тормозит. Размечай event_type, handler, result=ok|error|retry.
  • outbox_pending алёрт по абсолютному значению - при ночном batch-импорте 10K событий ложно срабатывает. Алёртить по age старейшей не-опубликованной записи (now - min(created_at) > 5min).
  • Логирование payload целиком - событие с email/телефоном/токеном попадает в логи, потом в централизованный сборщик. GDPR-инцидент. Логируй event_type, event_id, aggregate_id, метаданные - не содержимое payload.
  • Tracing включён только для HTTP, не для event consumer-ов - в Jaeger видно, что HTTP-запрос отдал ответ за 30ms, а почему email пришёл через 10 минут - никаких следов. OTel-инструментирование нужно и в consumer-ах: tracer.Start() на каждой обработке + извлечение span context из header события.
  • DLQ как «folder для забытых писем» - события попадают, никто не смотрит. Через год - десятки тысяч писем, разбор невозможен. Дежурный обязан проверять DLQ ежедневно, корневые причины фиксить, не накапливать.
  • Метрики обновляются «когда-нибудь после обработки» - defer metrics.Inc() без учёта успех/ошибка. Отметка error всё равно ставит processed_total++. Используй один счётчик с label-ом исхода, как events_processed_total{status="success|error"} выше, и считай долю ошибок через sum by (status).

Мини-задание

  • Добавь correlation_id в EventEnvelope и HTTP-middleware, который его генерирует
  • Настрой slog так, чтобы каждый лог содержал correlation_id, event_id и event_type
  • Зарегистрируй Prometheus-метрики: events_processed_total, event_processing_duration_seconds, outbox_pending_events
  • Реализуй ProcessWithRetry с exponential backoff и отправкой в DLQ после 3 попыток
  • Опиши 3 алерта для своей системы: на что срабатывают и какой порог

Зарегистрируйтесь бесплатно, чтобы пройти квиз, вести прогресс.