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 Laravel Package

dbstudios/prometheus-client

Lightweight Prometheus client for PHP. Create a CollectorRegistry, choose a storage adapter (Redis, Filesystem, APCu), then register and use counters, gauges, and histograms. Retrieve collectors by name with typed helpers for safer access.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Observability Alignment: The package aligns well with Laravel’s observability needs, particularly for metrics collection (counters, gauges, histograms) and Prometheus integration. It complements Laravel’s existing monitoring tools (e.g., Laravel Telescope, Sentry) by providing low-level metric instrumentation.
  • Prometheus Ecosystem: The package adheres to Prometheus’s metric types and labeling conventions, ensuring compatibility with Prometheus servers (e.g., Grafana, VictoriaMetrics) and alerting rules.
  • Laravel-Specific Gaps: While Laravel lacks built-in Prometheus support, this package fills the gap by offering a lightweight, PHP-native solution. However, it does not integrate with Laravel’s service container or event system out of the box, requiring manual setup.

Integration Feasibility

  • Low Friction: The package is designed for minimal setup (e.g., CollectorRegistry + adapter) and requires no Laravel-specific dependencies, reducing integration risk.
  • Adapter Flexibility: Supports Redis, filesystem, and APCu adapters, allowing TPMs to choose based on deployment constraints (e.g., Redis for distributed systems, filesystem for simplicity).
  • Manual Instrumentation: Requires explicit metric definitions (e.g., Counter, Gauge) and manual instrumentation in business logic (e.g., middleware, service layers). This contrasts with Laravel’s convention-over-configuration approach but aligns with Prometheus’s explicit metric design.

Technical Risk

  • Stale/Unmaintained: Last release in 2020 with minimal activity (2 stars, no dependents) raises concerns about long-term viability. Risk mitigation:
    • Fork the repo to apply critical fixes (e.g., PHP 8+ compatibility).
    • Monitor for upstream Prometheus spec changes (e.g., new metric types).
  • Performance Overhead: Adapters like Redis or filesystem may introduce latency if metrics are collected at high frequency (e.g., per-request). Benchmark under expected load.
  • Labeling Rigidity: Requires defining all labels upfront, which may complicate dynamic metrics (e.g., per-user tracking). Workaround: Use wildcards or label sets judiciously.
  • PHP Version: Requires PHP 7.3+. Laravel 9+ (PHP 8.0+) may need polyfills or forks for full compatibility.

Key Questions

  1. Adoption Strategy:
    • Should we fork the package to modernize it (e.g., PHP 8.1+, Laravel integration) or use it as-is with workarounds?
    • How will we handle metric naming/labeling consistency across microservices?
  2. Data Retention:
    • For filesystem/APCu adapters, how will we manage metric persistence (e.g., cron jobs to export to Prometheus)?
  3. Scaling:
    • What’s the expected metric volume (e.g., 10K requests/sec)? Will Redis/APCu bottleneck?
  4. Alternatives:
    • Compare with other PHP Prometheus clients (e.g., prometheus/client_php) or Laravel-specific tools (e.g., Spatie’s monitoring packages).
  5. Alerting:
    • How will Prometheus rules/alerts be defined and managed (e.g., GitOps, Terraform)?

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • Pros: No Laravel dependencies; works in any PHP 7.3+ app. Can be containerized alongside Laravel services.
    • Cons: No native integration with Laravel’s service container, events, or HTTP middleware. Requires manual wiring (e.g., bootstrapping CollectorRegistry in AppServiceProvider).
  • Observability Stack:
    • Prometheus Server: Compatible with any Prometheus-compatible server (e.g., Prometheus itself, Thanos for long-term storage).
    • Visualization: Works with Grafana (via Prometheus datasource) or other Prometheus-native tools.
    • Alerting: Integrates with Alertmanager for notifications.

Migration Path

  1. Pilot Phase:
    • Start with a single Laravel service (e.g., API) to instrument critical paths (e.g., request latency, error rates).
    • Use the Redis adapter for distributed metrics or filesystem for simplicity.
    • Example: Instrument Illuminate\Http\Middleware\HandleIncomingRequest to track request counts.
  2. Gradual Rollout:
    • Add metrics to other services (e.g., queues, jobs) using the same CollectorRegistry instance.
    • Replace manual instrumentation with Laravel-specific helpers (e.g., traits or macros) to reduce boilerplate.
  3. Prometheus Integration:
    • Expose metrics via a Laravel route (e.g., /metrics) using the TextRenderer.
    • Configure Prometheus to scrape this endpoint (e.g., scrape_configs in prometheus.yml).
  4. Fork/Modernize (Optional):
    • If long-term maintenance is a concern, fork the repo to:
      • Add PHP 8.1+ support.
      • Integrate with Laravel’s container (e.g., bind CollectorRegistry as a singleton).
      • Add Laravel-specific collectors (e.g., QueueJobCollector).

Compatibility

  • Laravel Versions: Tested on Laravel 6+ (PHP 7.3+). Laravel 9+ may need adjustments for PHP 8.1+ features (e.g., named arguments).
  • Adapter Constraints:
    • Redis: Requires Redis server (not ideal for serverless or edge deployments).
    • Filesystem: Risk of data loss if not backed up; not suitable for distributed setups.
    • APCu: Non-persistent; CLI support requires apc.enable_cli=1 in php.ini.
  • Prometheus Spec: Adheres to Prometheus 2.x. Verify compatibility if upgrading to Prometheus 3.x.

Sequencing

  1. Phase 1: Core Metrics (2–4 weeks):
    • Implement Counter for request counts, Histogram for latency, Gauge for active connections.
    • Validate Prometheus ingestion and basic dashboards.
  2. Phase 2: Business Metrics (2–3 weeks):
    • Add domain-specific metrics (e.g., order_processing_time, inventory_levels).
    • Integrate with Laravel events (e.g., job:failed) for richer telemetry.
  3. Phase 3: Alerting (1–2 weeks):
    • Define Prometheus rules for SLOs (e.g., error budget, latency percentiles).
    • Connect Alertmanager to Laravel’s notification channels (e.g., Slack, PagerDuty).
  4. Phase 4: Optimization (Ongoing):
    • Tune metric granularity (e.g., reduce labels for high-cardinality metrics).
    • Benchmark adapter performance under load.

Operational Impact

Maintenance

  • Library Updates: Monitor for Prometheus spec changes or PHP deprecations. Plan for annual dependency reviews.
  • Metric Schema: Document metric names/labels in a METRICS.md file to prevent drift. Use tools like OpenTelemetry’s semantic conventions for consistency.
  • Adapter Management:
    • Redis: Monitor memory usage; set up Redis eviction policies if needed.
    • Filesystem: Implement a cron job to rotate/backup metric files.
    • APCu: Accept transient data loss; use only for non-critical metrics.

Support

  • Debugging: Metrics may lag behind real-time events (e.g., APCu/Redis cache delays). Use CollectorRegistry::collect() to debug in-memory state.
  • Label Errors: Validate label values at runtime (e.g., whitelist allowed paths/methods) to catch misconfigurations early.
  • Prometheus Scraping: Ensure the /metrics endpoint is:
    • Accessible to Prometheus (no auth or rate-limiting).
    • Scraped at a reasonable interval (e.g., 15–60s for high-cardinality metrics).

Scaling

  • Horizontal Scaling:
    • Stateless Metrics: Use Redis for distributed counters/gauges (e.g., requests_total across Laravel instances).
    • Stateful Metrics: For per-instance metrics (e.g., memory usage), use filesystem/APCu with Prometheus’s scrape_interval tuned to instance count.
  • High Throughput:
    • Batch metric writes (e.g., flush to Redis/filesystem every 1000 increments).
    • Consider a dedicated queue for metric collection if instrumentation is heavy (e.g., per-DB-query metrics).
  • Cost: Redis/filesystem adapters add storage/network overhead. Monitor costs in cloud environments.

Failure Modes

Failure Scenario Impact Mitigation
Prometheus server down Metrics uncollected Use local storage (filesystem) as fallback; alert on scrape failures.
Redis/filesystem adapter failure Metrics lost Implement multi-adapter fallback (e.g., primary Redis + secondary filesystem).
PHP process crash (APCu) Transient metric loss Use Redis for critical metrics; accept APCu limitations for non-critical
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky