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

Metrics Laravel Package

directorytree/metrics

Record and query metrics in Laravel with a simple, elegant API. Track page views, API calls, signups, and other events with optional values, categories, dates, hourly buckets, model-scoped metrics, and custom attributes. Supports Redis and extensible drivers.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Laravel-native: Seamlessly integrates with Laravel’s ecosystem (Eloquent, Facades, Artisan commands) and follows Laravel conventions (e.g., migrations, service providers).
    • Modular Design: Supports customization via repositories, models, and managers, allowing alignment with existing architecture patterns (e.g., DDD, repository pattern).
    • Granularity Control: Offers daily/hourly metrics with optional Redis buffering, fitting both low-latency and high-throughput use cases.
    • Attribute Flexibility: Custom attributes enable segmentation (e.g., source, country) without schema bloat, leveraging Laravel’s dynamic query builder.
    • Model Association: HasMetrics trait integrates metrics with Eloquent models, enabling user/feature-specific analytics.
  • Gaps:

    • No Built-in Aggregation: Requires manual queries (e.g., groupBy, sum) for time-series analysis; lacks pre-built dashboards or real-time APIs.
    • Limited Time Windowing: Hourly metrics create 24x more rows; no native support for rolling windows (e.g., 7-day averages) or downsampling.
    • Redis Dependency: While optional, Redis driver adds complexity for distributed systems and requires manual scheduling (metrics:commit).
    • No Event Sourcing: Metrics are immutable post-commit; no support for auditing or replaying historical changes.

Integration Feasibility

  • High for Laravel Apps: Minimal friction with Laravel’s DI container, Eloquent, and Artisan. Composer install + migrations suffice for basic use.
  • Challenges:
    • Schema Customization: Extending the metrics table (e.g., adding user_id for segmentation) requires manual migrations and query adjustments.
    • Performance Tuning: Hourly metrics or high-volume apps may need:
      • Database indexing (e.g., name, category, date composite index).
      • Redis TTL adjustments to balance latency and retention.
    • Testing Overhead: Mocking Metrics facade or HasMetrics trait in unit tests requires setup (e.g., fake metrics, database transactions).

Technical Risk

  • Low for Core Use Cases: Recording and querying simple metrics (e.g., page_views, api_calls) is straightforward.
  • Medium for Advanced Scenarios:
    • Distributed Systems: Redis driver adds operational complexity (e.g., TTL management, commit scheduling).
    • High Cardinality: Custom attributes risk exploding row counts (e.g., user_id + device + country combinations).
    • Real-Time Analytics: No built-in caching or materialized views for dashboards; queries may time out under load.
  • Mitigation:
    • Benchmark Early: Test with production-like volumes (e.g., 10K metrics/hour) to validate Redis/database performance.
    • Isolate Critical Paths: Use Redis for high-frequency metrics (e.g., API calls) and direct DB writes for low-frequency ones (e.g., user_signups).
    • Monitor Query Plans: Optimize queries with EXPLAIN for complex segments (e.g., WHERE name LIKE 'api:%' AND category = 'users').

Key Questions

  1. Analytics Goals:
    • Are metrics primarily for internal dashboards, or do they feed into third-party tools (e.g., Mixpanel, Datadog)?
    • Do you need real-time aggregations (e.g., "active users in last 5 minutes") or batch processing?
  2. Data Retention:
    • How long should hourly/daily metrics be retained? (Affects indexing and storage costs.)
    • Are there compliance requirements (e.g., GDPR) for purging user-associated metrics?
  3. Scalability:
    • What’s the expected write volume? (e.g., 1M metrics/day → Redis buffering may be mandatory.)
    • Will metrics be queried globally (e.g., across regions) or per-tenant?
  4. Extensibility:
    • Do you need to extend the metric model (e.g., add tags or dimensions)?
    • Will custom attributes be static (e.g., source) or dynamic (e.g., user_preferences)?
  5. Observability:
    • How will you monitor metric collection failures (e.g., Redis outages, DB locks)?
    • Are there SLAs for metric accuracy (e.g., "99.9% of hourly metrics must commit within 1 hour")?

Integration Approach

Stack Fit

  • Ideal For:
    • Laravel Monoliths: Tight integration with Eloquent, Facades, and Artisan commands reduces boilerplate.
    • Serverless/Lambda: Redis driver decouples writes from DB commits, mitigating cold starts.
    • Hybrid Apps: Supports both web (e.g., page_views) and background (e.g., queue_jobs:failed) metrics.
  • Less Suited For:
    • Non-Laravel PHP: Requires Laravel’s DI container and Eloquent; not a standalone library.
    • Microservices: Cross-service metric aggregation would need a separate layer (e.g., Kafka + Prometheus).
    • Polyglot Persistence: No native support for non-SQL backends (e.g., DynamoDB, MongoDB).

Migration Path

  1. Pilot Phase:

    • Scope: Start with 2–3 high-impact metrics (e.g., user_signups, api_errors).
    • Implementation:
      • Install package + publish migrations.
      • Record metrics in critical paths (e.g., AuthController@register, ApiMiddleware).
      • Query via Tinker or a simple Blade template.
    • Validation: Verify data accuracy by cross-checking with logs or third-party tools.
  2. Core Integration:

    • Model Association: Add HasMetrics to key models (e.g., User, Order).
    • Custom Attributes: Extend the metrics table for segmentation (e.g., source, plan_type).
    • Redis Setup: Enable Redis driver for high-volume metrics (e.g., api_requests) and schedule metrics:commit.
    • Query Layer: Build a service class to abstract queries (e.g., AnalyticsService::getDailyActiveUsers()).
  3. Advanced Features:

    • Hourly Metrics: Enable only for time-sensitive use cases (e.g., peak_concurrency).
    • Capturing: Use Metrics::capture() in high-traffic endpoints (e.g., /checkout).
    • Testing: Mock metrics in unit tests with Metrics::fake() (if available) or database transactions.

Compatibility

  • Laravel Versions: Tested on Laravel 9+; PHP 8.1+ required. Check for breaking changes if upgrading.
  • Database: Supports MySQL, PostgreSQL, SQLite (via Eloquent). No native support for non-relational DBs.
  • Redis: Requires Redis 6+ for hashes and TTL. Configure metrics.php for connection details.
  • Queue Workers: If using Redis driver, ensure the metrics:commit command runs reliably (e.g., via Supervisor or Kubernetes CronJob).

Sequencing

  1. Pre-requisites:
    • Laravel 9+ with PHP 8.1+.
    • Redis server (if using Redis driver).
    • Database with sufficient write capacity (test with php artisan migrate --seed).
  2. Installation Order:
    • Composer install → Publish migrations → Run migrations → Publish config → Configure driver.
  3. Deployment:
    • Blue-Green: Deploy Redis driver changes first to avoid data loss.
    • Rollback Plan: Disable auto-commit ('auto_commit' => false) if metrics:commit fails.
  4. Post-Launch:
    • Set up monitoring for:
      • Redis memory usage (if using driver).
      • Database lock contention on metrics table.
      • Failed metrics:commit jobs.

Operational Impact

Maintenance

  • Pros:
    • Low Code Maintenance: Package handles CRUD, migrations, and basic queries.
    • Centralized Config: Driver, TTL, and queue settings in config/metrics.php.
    • Artisan Commands: metrics:commit, metrics:clear (if added) for manual intervention.
  • Cons:
    • Schema Drift Risk: Custom attributes require manual migration updates.
    • Dependency Updates: Laravel/PHP version upgrades may need package version alignment.
    • Redis Management: If using Redis driver, monitor:
      • Memory usage (TTL + hash growth).
      • Commit job failures (e.g., DB connection issues).

Support

  • Debugging:
    • Common Issues:
      • Metrics not recording: Check auto_commit setting, middleware, or exceptions.
      • Redis metrics lost: Verify TTL and metrics:commit scheduling.
      • Slow queries: Add indexes to name, category, and date columns.
    • Tools:
      • Laravel Debugbar to inspect queries.
      • Redis CLI (HGETALL metrics:pending) to debug buffered metrics.
      • `php artisan t
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle