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

zackaj/laravel-debounce

Debounce Laravel jobs, notifications, and (Laravel 11+) Artisan commands to prevent spamming users and queues. Uses unique job locks + cache to delay execution until activity stops. Tracks each occurrence with request metadata (IP, user) and provides reporting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require zackaj/laravel-debounce
    

    Publish config (optional):

    php artisan vendor:publish --tag=laravel-debounce-config
    
  2. First Use Case: Debounce a notification to prevent spamming users with repeated alerts:

    use Zackaj\LaravelDebounce\Facades\Debounce;
    
    Debounce::notification(
        notifiables: $users,
        notification: new FileUploaded($file),
        delay: 5, // 5 seconds
        uniqueKey: $userId
    );
    

Where to Look First

  • Facade Usage: Zackaj\LaravelDebounce\Facades\Debounce for quick integration.
  • Configuration: config/debounce.php for enabling/disabling debouncing globally.
  • Report Tracking: Extend DebounceJob, DebounceNotification, or DebounceCommand for tracking occurrences.

Implementation Patterns

Core Workflows

  1. Debouncing Jobs:

    Debounce::job(
        job: new ProcessPayment($order),
        delay: 10,
        uniqueKey: $order->id,
        sync: false // Dispatch to queue
    );
    
    • Key: Use uniqueKey to group related jobs (e.g., user_id, order_id).
    • Sync vs Queue: Set sync: true for synchronous execution (bypasses queue).
  2. Debouncing Notifications:

    Debounce::notification(
        notifiables: $user,
        notification: new WelcomeEmail(),
        delay: 30,
        uniqueKey: $user->email,
        sendNow: false // Queue the notification
    );
    
    • Key: Use sendNow: false to defer sending via the queue.
    • Notifiables: Supports single users or collections.
  3. Debouncing Artisan Commands (Laravel ≥11):

    Debounce::command(
        command: 'report:generate',
        delay: 60,
        uniqueKey: 'daily-report',
        parameters: ['--format' => 'pdf'],
        toQueue: true
    );
    
    • Key: Use toQueue: true to execute asynchronously.
    • CLI Alternative: Run via Artisan:
      php artisan debounce:command 60 daily-report report:generate --format=pdf
      

Integration Tips

  1. Extend Base Classes for advanced features:

    class SendWelcomeEmail extends DebounceNotification {
        public function before($notifiables) {
            // Pre-send logic (e.g., log, validate)
        }
    
        public function getLastActivityTimestamp($notifiables) {
            return $notifiables->lastLoginAt; // Custom timestamp logic
        }
    }
    
  2. Report Tracking: Access occurrence history in jobs/notifications:

    $report = $this->getReport();
    $report->occurrences->count(); // Total attempts
    $report->occurrences->first()->ip; // First request IP
    
  3. Testing: Disable debouncing in tests:

    config(['debounce.enabled' => false]);
    

    Or via .env.testing:

    LARAVEL_DEBOUNCE_ENABLED=false
    

Gotchas and Tips

Pitfalls

  1. Cache Dependence:

    • Reports and locks are stored in cache. Flushing cache (php artisan cache:clear) resets all debounced states.
    • Workaround: Use a persistent cache driver (e.g., Redis) for production.
  2. Artisan Command Limitations (Laravel <11):

    • CLI debouncing is disabled in Laravel 10. Use the facade or extend DebounceCommand instead.
  3. Hook Timing:

    • after() hooks may run before queue dispatch if sync: false and the job implements ShouldQueue.
    • Fix: Use sync: true for immediate execution or handle async logic in handle().
  4. Unique Key Collisions:

    • Poorly chosen uniqueKey values (e.g., static strings) can merge unrelated debounce groups.
    • Tip: Use dynamic keys like user_id, order_id, or ip + timestamp.

Debugging Tips

  1. Telescope Integration:

    • Monitor debounced jobs/notifications in Laravel Telescope’s Queues tab.
    • Setup: Ensure telecope is installed and configured.
  2. Log Occurrences:

    $this->getReport()->occurrences->each(function ($occurrence) {
        Log::info('Debounce attempt', ['ip' => $occurrence->ip, 'user' => $occurrence->user]);
    });
    
  3. Manual Lock Inspection:

    • Check cache for locks:
      php artisan cache:table
      
    • Look for keys prefixed with laravel-debounce:.

Extension Points

  1. Custom Drivers:

    • Extend the Zackaj\LaravelDebounce\Contracts\DebounceDriver interface to support non-cache backends (e.g., database).
  2. Dynamic Delays:

    public function getDelay(): int {
        return $this->user->isPremium() ? 30 : 60; // Dynamic delay logic
    }
    
  3. Global Overrides:

    • Override config/debounce.php defaults:
      'default_delay' => 30, // Global fallback delay
      'report_ttl' => 604800, // Report retention in seconds
      

Pro Tips

  • Bulk Operations: Use uniqueKey to debounce batch processes (e.g., user_id + action_type).
  • Fallback Logic: Implement getLastActivityTimestamp() to debounce based on domain-specific events (e.g., Message::latest()->first()?->seen_at).
  • Environment-Specific Delays:
    $delay = config('app.env') === 'production' ? 300 : 5; // 5s in dev, 5m in prod
    
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