Magento 2 OpenTelemetry Instrumentation

May 26, 2026 ยท View on GitHub

Magento 2 Opentelemetry Instrumentation

Magento 2 OpenTelemetry Instrumentation

OpenTelemetry integration package for Magento 2 applications with complete observability stack

Packagist Version Packagist Downloads Supported Magento Versions License

๐Ÿ“– Overview

A Composer library that adds OpenTelemetry tracing to Magento 2. It hooks into Magento core classes at runtime to automatically create spans for:

  • HTTP requests โ€” REST API, GraphQL, Backend admin, HTTP client
  • Database โ€” SQL query tracing
  • Cache โ€” Page cache, Redis, Varnish
  • CLI โ€” Commands, cron jobs, indexer operations
  • Entity โ€” EAV and flat entity load/save
  • Business logic โ€” Pricing, shipping, inventory, sales rules, repositories

๐Ÿ”„ OpenTelemetry Flow

OpenTelemetry Flow

๐Ÿ“Š Grafana Traces

Grafana Traces

โš™๏ธ How OpenTelemetry PHP SDK Works Under the Hood

1. PHP registers shutdown handler:
   OpenTelemetry\SDK\Common\Util\ShutdownHandler::register()

2. During shutdown:
   โ”‚
   โ””โ”€> OpenTelemetry\SDK\Common\Util\ShutdownHandler::handleShutdown()
       โ”‚
       โ””โ”€> Executes registered callbacks including:
           โ”‚
           โ””โ”€> OpenTelemetry\SDK\Trace\TracerProvider->shutdown()
               โ”‚
               โ””โ”€> Delegates to:
                   โ”‚
                   โ””โ”€> OpenTelemetry\SDK\Trace\TracerSharedState->shutdown()
                       โ”‚
                       โ””โ”€> Processes all span processors:
                           โ”‚
                           โ””โ”€> OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor->shutdown()
                               โ”‚
                               โ””โ”€> Final flush:
                                   โ”‚
                                   โ””โ”€> OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor->flush()
                                       โ”‚
                                       โ””โ”€> Delegates export to:
                                           โ”‚
                                           โ””โ”€> OpenTelemetry\Contrib\Otlp\SpanExporter->export()
                                               โ”‚
                                               โ”œโ”€> Serializes spans
                                               โ””โ”€> Makes network call to collector

๐Ÿ“‹ Prerequisites

  • PHP 8.0+
  • PECL
  • Composer
  • OpenTelemetry PHP extension + PHP SDK
  • Magento Application
    • Docker
    • Host

๐Ÿ”ง OpenTelemetry Setup

1. Install OpenTelemetry PHP Extension

pecl install opentelemetry

2. Configure the .ini Settings

Add the following to your PHP .ini file (e.g. php.ini or a custom opentelemetry.ini):

OTEL_PHP_AUTOLOAD_ENABLED="true"
OTEL_SERVICE_NAME=magento2
OTEL_TRACES_EXPORTER=otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://[COLLECTOR-IP]:4318
OTEL_PROPAGATORS=baggage,tracecontext
;OTEL_PHP_DISABLED_INSTRUMENTATIONS=magento2
;OTEL_PHP_EXCLUDED_URLS="health_check.php,get.php"

3. Verify the Extension

php -m | grep opentelemetry
php --ri opentelemetry

4. Install the PHP SDK

composer require open-telemetry/sdk open-telemetry/api open-telemetry/sem-conv open-telemetry/exporter-otlp

Note: These packages are automatically installed as dependencies when you install mumzworld/magento2-opentelemetry. You only need to install them manually if you're setting up OpenTelemetry without this package.

๐Ÿ“ฆ Package Installation

composer require mumzworld/magento2-opentelemetry

No Magento module setup is needed โ€” the package bootstraps automatically via Composer's autoload mechanism.

๐Ÿ” What Is Auto-Instrumented

Once installed, this package automatically instruments the following Magento areas โ€” no code changes required.

Core

InstrumentationHooked ClassMethod
Magento BootstrapMagento\Framework\App\Bootstraprun(), terminate()
Exception HandlingMagento\Framework\App\HttpcatchException()
ProfilerMagento\Framework\Profilerstart(), stop()
Event ObserversMagento\Framework\Event\InvokerInterfacedispatch()

HTTP

InstrumentationHooked ClassMethod
REST APIMagento\Webapi\Controller\Rest\Interceptordispatch()
REST ExceptionsMagento\Framework\Webapi\Exception__construct()
GraphQL DispatchMagento\GraphQl\Controller\GraphQl\Interceptordispatch()
GraphQL QueryMagento\Framework\GraphQl\Query\QueryProcessorprocess()
GraphQL ResolverMagento\Framework\GraphQl\Query\ResolverInterfaceresolve()
Backend AdminMagento\Backend\App\AbstractActiondispatch()
HTTP ClientGuzzleHttp\Clientsend()

Database

InstrumentationHooked ClassMethod
SQL QueriesMagento\Framework\DB\Adapter\Pdo\Mysqlquery()

Cache

InstrumentationHooked ClassMethod
FormKey FlushMagento\PageCache\Observer\FlushFormKey\Interceptorexecute()
Full Cache FlushMagento\CacheInvalidate\Observer\FlushAllCacheObserverexecute()
Cache InvalidationMagento\PageCache\Observer\InvalidateCacheexecute()
RedisMagento\Framework\Cache\Backend\Redistest(), save(), remove(), clean()
Varnish PurgeMagento\CacheInvalidate\Model\PurgeCachesendPurgeRequest()

CLI

InstrumentationHooked ClassMethod
CLI RunnerMagento\Framework\Console\ClidoRun()
Console CommandsSymfony\Component\Console\Command\Commandrun()
Cron JobsMagento\Cron\Observer\ProcessCronQueueObservertryRunJob()
ReindexMagento\Indexer\Model\ProcessorreindexAllInvalid()
Mview ActionsMagento\Framework\Mview\ViewexecuteAction()
Mview ExecuteMagento\Framework\Mview\ActionInterfaceexecute()
Mview ChangelogMagento\Framework\Mview\View\ChangelogInterfaceclear()

Entity (EAV)

InstrumentationHooked ClassMethod
ProductMagento\Catalog\Model\ResourceModel\Product\Interceptorload(), save(), delete()
CategoryMagento\Catalog\Model\ResourceModel\Category\Interceptorload(), save(), delete()
CustomerMagento\Customer\Model\ResourceModel\Customer\Interceptorload(), save(), delete()
Customer AddressMagento\Customer\Model\ResourceModel\Address\Interceptorload(), save(), delete()

Entity (Flat)

InstrumentationHooked ClassMethod
QuoteMagento\Quote\Model\ResourceModel\Quoteload(), save(), delete()
Quote ItemMagento\Quote\Model\ResourceModel\Quote\Itemload(), save(), delete()
OrderMagento\Sales\Model\ResourceModel\Orderload(), save(), delete()
Order ItemMagento\Sales\Model\ResourceModel\Order\Itemload(), save(), delete()
InvoiceMagento\Sales\Model\ResourceModel\Order\Invoiceload(), save(), delete()
Credit MemoMagento\Sales\Model\ResourceModel\Order\Creditmemoload(), save(), delete()

Business Logic (Misc)

Opt-in. This group is disabled by default โ€” it produces the highest-volume spans (per-rule sales-rule evaluation, repository calls, pricing/tax calculation, address totals, etc.) and is best enabled selectively. Activate it by setting OTEL_MAGENTO_MISC_INSTRUMENTATION=true in your environment (.env, docker-compose.yml, nginx fastcgi_param, php-fpm pool, or export for CLI).

InstrumentationHooked ClassMethod
Abstract DBMagento\Framework\Model\ResourceModel\Db\AbstractDbload(), save(), delete()
Product RepositoryMagento\Catalog\Model\ProductRepositoryget(), getById()
Category RepositoryMagento\Catalog\Model\CategoryRepositoryget()
Customer RepositoryMagento\Customer\Model\ResourceModel\CustomerRepositoryget(), getById()
Shipping RatesMagento\Shipping\Model\ShippingcollectRates()
Final PriceMagento\Catalog\Model\Product\Type\PricegetFinalPrice(), _applyTierPrice()
Tax CalculationMagento\Tax\Model\CalculationgetRate()
Sales RulesMagento\SalesRule\Model\Validatorprocess()
InventoryMagento\CatalogInventory\Observer\QuantityValidatorObserverexecute()
Totals CollectorMagento\Quote\Model\Quote\TotalsCollector\InterceptorcollectAddressTotals()
Address TotalsMagento\Quote\Model\Quote\Address\Total\AbstractTotalcollect()
Totals CollectorMagento\Quote\Model\Quote\Address\Total\Collectorcollect()
Discount CalcMagento\SalesRule\Model\Rule\Action\Discount\AbstractDiscountcalculate()

๐Ÿš€ Optimization Tips

Install ext-protobuf PHP Extension

Preferred over the pure-PHP library google/protobuf for production:

pecl install protobuf
OptionPackagePerformance
C extension (recommended)ext-protobuf via pecl install protobufNative speed, minimal overhead
Pure-PHP librarygoogle/protobuf via ComposerSlower serialization, higher CPU usage

NOTE: To reduce the latency imposed by the OTel exporter:

  1. Use a local OTel collector (instead of remote)
  2. Use the ext-protobuf C extension instead of the Composer package

Limiting the Number of Spans

See OpenTelemetry SDK Environment Variables โ€” Attribute Limits for details on:

  • Limiting the number of span attributes
  • Limiting the length of span attribute values
  • Limiting the number of events

Export Settings

SettingPurposeDefaultSuggestedEffect of Tuning
OTEL_BSP_MAX_QUEUE_SIZEMax number of spans buffered in memory204810000+Prevents spans being dropped under high load
OTEL_BSP_MAX_EXPORT_BATCH_SIZEMax spans exported per batch5121000โ€“5000Reduces export cycles, improves throughput
OTEL_BSP_SCHEDULE_DELAYHow often (ms) the processor checks the queue for exporting5000 ms100โ€“200 msFaster flushing during long-running requests
OTEL_BSP_EXPORT_TIMEOUTMax time (ms) allowed for a single export batch30000 ms1000โ€“2000 msPrevents request shutdown from blocking if exporter is slow/hangs

โšก Performance Considerations

  • Sampling: Use appropriate sampling rates for production (0.1 = 10%)
  • Batching: Configure batch processors in collector
  • Resource Limits: Set memory and CPU limits
  • Network: Use gRPC for better performance
  • Storage: Configure appropriate retention policies

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

๐Ÿ“„ License

This package is licensed under the MIT License.

๐Ÿ’ฌ Support

For support and questions:


Built with โค๏ธ by Mumzworld Development Team