Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Prometheus Client Php Laravel Package

promphp/prometheus_client_php

Prometheus client library for PHP with Redis or APCu-based aggregation (plus in-memory adapter). Register and update counters, gauges, histograms, and summaries via CollectorRegistry, then expose metrics in Prometheus text format for scraping.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Observability Alignment: The package excels as a Prometheus instrumentation library for Laravel/PHP applications, enabling standardized metrics collection (counters, gauges, histograms, summaries) with multi-process support via Redis/APCu adapters. This aligns with modern observability stacks (e.g., Prometheus + Grafana) and complements Laravel’s existing logging/debugging tools.
  • Laravel Integration: Laravel’s service container and middleware pipeline can natively host the CollectorRegistry and expose metrics via HTTP routes (e.g., /metrics). The package’s stateless design (except for storage backends) avoids conflicts with Laravel’s request lifecycle.
  • Extensibility: Supports custom storage backends (PDO, Redis, APCu) and label-based metrics, enabling granular tagging (e.g., service:laravel, environment:production). This fits Laravel’s modular architecture (e.g., packages like spatie/laravel-metrics).

Integration Feasibility

  • Low Friction: Composer-based installation and minimal boilerplate (e.g., getOrRegisterCounter()) reduce integration effort. Laravel’s service providers can initialize the registry and storage adapter on boot.
  • Middleware Hooks: Metrics can be auto-instrumented via Laravel middleware (e.g., track request latency, HTTP status codes) or event listeners (e.g., queue jobs, cron tasks).
  • Prometheus Scraping: The /metrics endpoint can be exposed via Laravel’s routing system, with authentication (e.g., basic auth, IP whitelisting) added via middleware.

Technical Risk

  • Storage Backend Dependencies:
    • Redis: Requires a separate Redis instance (or APCu/Predis), adding operational overhead. Redis failures could silence metrics unless fallback adapters (e.g., in-memory) are configured.
    • APCu: Shared-memory storage may corrupt metrics if PHP workers crash mid-update (mitigated by the package’s lock-free optimizations in v2.8+).
  • Performance:
    • Redis/Predis adapters introduce network latency for metric aggregation. Benchmarking is critical for high-throughput apps (e.g., Laravel queues).
    • In-memory adapter is not persistent across requests (suitable only for short-lived scripts).
  • Laravel-Specific Risks:
    • Queue Workers: Metrics from background jobs (e.g., Laravel Horizon) require Redis/Predis for cross-process consistency.
    • Artisan Commands: Long-running CLI tasks may need custom storage (e.g., PDO) to persist metrics.

Key Questions

  1. Storage Strategy:
    • Will Redis/APCu be co-located with Laravel workers, or will a dedicated Prometheus Push Gateway (via promphp/prometheus_push_gateway_php) be used?
    • For multi-server deployments, how will metric consistency be ensured across instances?
  2. Performance:
    • What is the expected metric cardinality (e.g., labels per metric)? High cardinality may strain Redis memory.
    • Are there bottlenecks in Laravel’s request pipeline when exposing /metrics?
  3. Failure Modes:
    • How will storage failures (e.g., Redis downtime) be handled? Fallback to in-memory with alerts?
    • Will metrics be sampled to reduce volume (e.g., via Prometheus’ scrape_interval)?
  4. Laravel Ecosystem:
    • Will this replace or complement existing monitoring (e.g., Laravel Telescope, Sentry)?
    • How will metrics be correlated with logs/traces (e.g., OpenTelemetry integration)?

Integration Approach

Stack Fit

  • Laravel Core:
    • Service Provider: Register CollectorRegistry and storage adapter in AppServiceProvider::boot().
    • Middleware: Auto-instrument routes (e.g., track response_time_ms via Kernel::handle()).
    • Routing: Expose /metrics endpoint with auth middleware.
  • Storage Backend:
    • Redis: Preferred for multi-process apps (e.g., queues, cron). Use Predis for connection pooling.
    • APCu: Lightweight but risky for long-running processes (e.g., CLI tasks).
    • PDO: For persistent storage (e.g., SQLite/PostgreSQL) in air-gapped environments.
  • Prometheus Integration:
    • Configure Prometheus scrape_configs to target Laravel’s /metrics endpoint.
    • Use relabeling to standardize metric names (e.g., prefix with laravel_).

Migration Path

  1. Pilot Phase:
    • Instrument non-critical routes (e.g., /health) with basic counters (e.g., http_requests_total).
    • Validate metrics appear in Prometheus and Grafana.
  2. Core Integration:
    • Add middleware to track request latency, error rates, and queue job metrics.
    • Replace custom logging with structured metrics (e.g., database_query_duration_seconds).
  3. Advanced Use Cases:
    • Instrument Laravel Queues (e.g., job_processing_time_seconds).
    • Use histograms for latency percentiles (e.g., P99 response times).
    • Implement custom collectors for Laravel-specific events (e.g., auth_attempts_total).

Compatibility

  • Laravel Versions: Supports PHP 8.2+, compatible with Laravel 10+.
  • Existing Tools:
    • Prometheus Client PHP: No conflicts with Laravel’s core; operates at the application layer.
    • Laravel Packages: Can coexist with spatie/laravel-metrics (if using different storage backends).
  • Storage Backend Quirks:
    • Redis: Ensure predis/predis is installed for Predis support.
    • APCu: Requires pecl install apcu and PHP apcu.enable_cli=1 for CLI metrics.
    • PDO: Test with target database (e.g., PostgreSQL/MySQL) for schema compatibility.

Sequencing

  1. Setup Storage:
    • Deploy Redis (or configure APCu/PDO) before Laravel integration.
  2. Initialize Registry:
    // config/app.php
    'prometheus' => [
        'adapter' => env('PROMETHEUS_ADAPTER', 'redis'),
        'redis' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'port' => env('REDIS_PORT', 6379),
        ],
    ];
    
  3. Bootstrap in Laravel:
    // app/Providers/AppServiceProvider.php
    public function boot(): void
    {
        $adapter = config('prometheus.adapter');
        $registry = new CollectorRegistry(
            match ($adapter) {
                'redis' => new Redis(),
                'predis' => new Predis(),
                'apcu' => new APCu(),
                default => new InMemory(),
            }
        );
        app()->singleton('prometheus.registry', fn() => $registry);
    }
    
  4. Expose Metrics:
    // routes/web.php
    Route::get('/metrics', function () {
        $registry = app('prometheus.registry');
        $renderer = new RenderTextFormat();
        header('Content-type: ' . RenderTextFormat::MIME_TYPE);
        return $renderer->render($registry->getMetricFamilySamples());
    })->middleware('auth:prometheus');
    
  5. Instrument Business Logic:
    // Example: Track API requests
    Route::middleware(['metrics'])->group(function () {
        Route::get('/api/users', [UserController::class, 'index']);
    });
    

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor promphp/prometheus_client_php for PHP 8.5+ compatibility and storage adapter improvements.
    • Update predis/predis or php-redis if using Redis.
  • Metric Schema:
    • Document metric naming conventions (e.g., laravel_http_requests_total) to avoid breaking Prometheus queries.
    • Use Prometheus’ relabel to standardize labels (e.g., job=laravel_app).
  • Storage Management:
    • Redis: Monitor memory usage (redis-cli info memory). Set maxmemory-policy to allkeys-lru.
    • APCu: Tune apc.shm_size to avoid evictions.
    • PDO: Schedule database maintenance for metric tables.

Support

  • Troubleshooting:
    • Missing Metrics: Verify storage backend connectivity (e.g., Redis ping).
    • Corrupted Data: Check for Redis/PHP crashes during metric updates. Use APCng for CLI stability.
    • High Latency: Profile metric collection in Laravel’s request lifecycle (e.g., tideways/xhprof).
  • Alerting:

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests