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

Laravel Top Laravel Package

leventcz/laravel-top

Real-time, lightweight monitoring for Laravel from the CLI. Listens to request events, aggregates short-lived metrics in Redis, and displays 5-second averages across all app servers. Ideal for production to spot load, latency, and busiest routes.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Add the package via Composer:
    composer require leventcz/laravel-top
    
  2. Verify Redis: Ensure Redis 5.0+ is running and configured in config/database.php (default connection works).
  3. Publish Config (Optional): Customize settings with:
    php artisan vendor:publish --tag="top"
    
  4. First Command: Run in production or staging:
    php artisan top
    
    • Expected Output: Real-time dashboard showing:
      • HTTP request metrics (RPS, avg duration, memory)
      • Database query stats (QPS, avg duration)
      • Cache performance (hits/misses/sec)
      • Top 20 busiest routes (URI, method, metrics)
  5. Quick Check: Use during deployments or load spikes to validate performance.

Implementation Patterns

Daily Workflows

  1. Incident Response:

    • Run php artisan top in a separate terminal during outages to monitor live metrics.
    • Filter routes by averageDuration to identify bottlenecks (e.g., >500ms).
    • Example:
      php artisan top --filter="duration>500"
      
  2. Post-Deployment Validation:

    • Compare pre/post-deployment metrics using the facade:
      $routes = Top::routes()->where('averageDuration', '>', 300)->values('uri');
      // Log or alert on degraded routes.
      
  3. Load Testing:

    • Use Top::startRecording() to capture metrics during artificial load:
      Top::startRecording(30); // Record for 30 seconds
      // Simulate traffic...
      $summary = Top::http();
      
  4. Custom Monitoring:

    • Embed metrics in admin panels or Slack alerts:
      $criticalRoutes = Top::routes()
          ->where('averageMemoryUsage', '>', 1000) // >1MB
          ->pluck('uri');
      

Integration Tips

  • Redis Connection: Use a dedicated Redis DB (e.g., config['top']['connection'] = 'cache') to avoid cluttering the default DB.
  • Octane Compatibility: Works seamlessly with Laravel Octane’s real-time features—metrics reflect all server instances.
  • CI/CD: Add php artisan top to deployment scripts to validate performance post-merge.
  • Facade Caching: Cache facade results for dashboards (e.g., Cache::remember('top_metrics', 10, fn() => Top::http())).

Gotchas and Tips

Pitfalls

  1. Redis Dependency:

    • Issue: Package fails silently if Redis is down (no fallback).
    • Fix: Wrap facade calls in try-catch:
      try {
          $metrics = Top::http();
      } catch (\RedisException $e) {
          Log::error("Top metrics unavailable: Redis down", ['error' => $e]);
      }
      
  2. Recording Mode Quirks:

    • recording_mode=always only works during HTTP requests (queues/commands are ignored).
    • Workaround: Use Top::startRecording() for manual control.
  3. Preflight Requests:

    • Laravel’s preflight OPTIONS requests may skew metrics (e.g., CORS routes).
    • Mitigation: Exclude them via middleware or filter:
      $routes = Top::routes()->where('method', '!=', 'OPTIONS');
      
  4. Memory Spikes:

    • High-traffic routes (>1k RPS) may cause Redis memory bloat.
    • Solution: Monitor Redis memory usage and adjust TTL (default: 5s).

Debugging Tips

  • No Data?:

    • Verify Redis is running: redis-cli ping.
    • Check recording_mode in config/top.php (default: runtime).
    • Ensure Laravel events are firing (e.g., Illuminate\Http\RequestHandled).
  • Stale Metrics:

    • The 5-second aggregation window may lag during spikes.
    • Fix: Reduce TTL in Redis (requires customizing the package’s TTL constant).
  • Facade Errors:

    • Clear cached facades:
      composer dump-autoload
      php artisan optimize:clear
      

Extension Points

  1. Custom Metrics:

    • Extend the Leventcz\Top\Events\MetricCollected event to log additional data:
      Top::extend(function ($collector) {
          $collector->custom('custom_metric', fn() => memory_get_usage(true));
      });
      
  2. Route Filtering:

    • Override the route list logic in app/Providers/TopServiceProvider.php:
      public function boot()
      {
          Top::macro('filterRoutes', function ($callback) {
              return $this->routes()->filter($callback);
          });
      }
      
  3. Output Formatting:

    • Customize the CLI output by extending the Leventcz\Top\Console\TopCommand class.

Config Quirks

  • Redis Connection: Must match Laravel’s config/database.php keys (e.g., default, cache).
  • TTL Override: Modify the package’s TTL constant (default: 5s) in vendor/leventcz/laravel-top/src/TopServiceProvider.php (not recommended for production).
  • Environment-Specific Settings: Use environment variables:
    TOP_REDIS_CONNECTION=cache
    TOP_RECORDING_MODE=always
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai