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

Nats Laravel Package

basis-company/nats

PHP NATS client with support for TLS and JWT auth, pub/sub and request/reply patterns, plus JetStream APIs (microservices, key-value storage). Configurable reconnect and retry delays. Install via Composer and connect with simple configuration.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & Microservices Alignment: The package excels in Laravel/Lumen applications leveraging event-driven architectures, microservices, or asynchronous workflows (e.g., job queues, real-time notifications, or distributed task processing). NATS JetStream’s persistent streams, consumers, and key-value storage align well with Laravel’s queues (e.g., Illuminate\Queue) but offer higher throughput and advanced features (e.g., message retention, batching, ephemeral consumers).
  • Replacement for Redis/RabbitMQ: Ideal for teams migrating from Redis queues or RabbitMQ to NATS for scalability (360k+ RPS) or cost efficiency (single binary, no broker clustering overhead).
  • Laravel Integration Gaps: While Laravel’s built-in queue system (e.g., database, redis) is simpler, this package enables JetStream-specific features (e.g., work queues, stream configurations, microservices routing) not natively supported in Laravel.

Integration Feasibility

  • Laravel Service Provider: The package can be bootstrapped via a Laravel Service Provider to:
    • Register a NATS client singleton (e.g., app['nats']).
    • Bind JetStream API to Laravel’s container for dependency injection.
    • Extend Laravel’s queue system with NATS drivers (e.g., NatsQueue).
  • Event System Hooks: Integrate with Laravel’s events by:
    • Publishing events to NATS subjects (e.g., user.created).
    • Subscribing to NATS subjects and dispatching Laravel events (e.g., Event::dispatch(new UserCreated(...))).
  • Job Queues: Replace Laravel’s queue workers with NATS consumers:
    $client->getApi()->getStream('jobs')->getConsumer('worker')->handle(function ($job) {
        dispatch(new ProcessJob($job->payload));
    });
    
  • API Gateway Pattern: Use NATS microservices to route requests (e.g., v1.users.*) to Laravel API endpoints or external services.

Technical Risk

Risk Area Mitigation Strategy
Connection Management Use Laravel’s container binding to manage NATS client lifecycle (singleton).
Error Handling Implement retry logic (exponential backoff) for failed publishes/acks.
Schema Mismatches Validate NATS payloads against Laravel’s Form Requests or DTOs.
Performance Bottlenecks Benchmark against Laravel’s default queues; optimize batching (e.g., fetchAll).
Security Enforce TLS/JWT in NATS config; restrict Laravel routes to NATS-authenticated clients.
State Management Use NATS key-value storage for shared state (e.g., cache, config) instead of Redis.

Key Questions

  1. Use Case Priority:
    • Is NATS needed for high-throughput messaging (e.g., IoT, real-time analytics) or simpler queue replacement?
    • Will Laravel’s built-in queues suffice, or are JetStream features (e.g., work queues, stream retention) critical?
  2. Infrastructure:
    • Is NATS already deployed (e.g., Kubernetes, Docker) or needs provisioning?
    • Are TLS/JWT requirements aligned with Laravel’s security policies?
  3. Team Expertise:
    • Does the team have experience with event-driven architectures or NATS?
    • Is there budget for performance testing (e.g., load testing NATS vs. Redis queues)?
  4. Migration Path:
    • Should NATS coexist with existing queues (e.g., dual-writing to Redis and NATS) or replace them?
    • Are there legacy systems (e.g., Python/Go services) already using NATS that Laravel must integrate with?

Integration Approach

Stack Fit

  • Laravel 9/10: Compatible with PHP 8.1+; leverages PSR-15 middleware for request/response handling.
  • Dependencies:
    • libsodium (for NKey/JWT) or sodium_compat (fallback).
    • PHP Extensions: No additional extensions required beyond php-nats (if using raw NATS).
  • Tooling:
    • Laravel Horizon: Can be extended to monitor NATS consumers/streams.
    • Telescope: Log NATS events (e.g., message publishes, consumer metrics).

Migration Path

Phase Action Tools/Libraries
Evaluation Benchmark NATS vs. Laravel’s default queues (e.g., Redis). phpbench, k6
Pilot Replace a non-critical queue (e.g., notifications) with NATS. Laravel Service Provider, NATS PHP SDK
Core Integration Extend Laravel’s queue system with NATS drivers (e.g., NatsQueue). Laravel Queue Workers, NATS Consumers
Event System Replace bus or events with NATS subjects (e.g., user.created → NATS publish). Laravel Events, NATS Pub/Sub
Microservices Route API requests via NATS (e.g., v1.users.*) to Laravel or external services. NATS Microservices API
Key-Value Store Migrate Redis cache/config to NATS JetStream buckets. NATS Key-Value API

Compatibility

  • Laravel Queues:
    • Replace Illuminate\Queue\Queue with a NATS driver wrapping Basis\Nats\Client.
    • Example:
      $client = app('nats');
      $client->getApi()->getStream('laravel-jobs')->getConsumer('worker')->handle(function ($job) {
          dispatch(new ProcessJob($job->payload));
      });
      
  • Laravel Events:
    • Publish events to NATS:
      event(new UserCreated($user));
      // In listener:
      $client->publish('user.created', json_encode($user));
      
    • Subscribe to NATS and dispatch Laravel events:
      $client->subscribe('user.created', function ($message) {
          Event::dispatch(new NatsUserCreated(json_decode($message->payload, true)));
      });
      
  • API Routes:
    • Use NATS microservices to route requests:
      $service = $client->service('LaravelAPI', 'Handles HTTP requests via NATS');
      $v1 = $service->addGroup('v1');
      $v1->addEndpoint('users', function ($payload) {
          return response()->json(User::all());
      });
      

Sequencing

  1. Infrastructure Setup:
    • Deploy NATS server (e.g., Kubernetes, Docker) with JetStream enabled.
    • Configure TLS/JWT if required.
  2. Laravel Integration:
    • Add basis-company/nats to composer.json.
    • Register NATS client in AppServiceProvider:
      public function register()
      {
          $this->app->singleton('nats', function () {
              return new Client(new Configuration(host: 'nats-service'));
          });
      }
      
  3. Queue Migration:
    • Replace RedisQueue with NatsQueue for non-critical jobs.
    • Update App\Jobs to use NATS consumers.
  4. Event System:
    • Add NATS listeners for critical events (e.g., user.created).
  5. Microservices:
    • Gradually route API endpoints via NATS (e.g., v1.*).
  6. Monitoring:
    • Integrate NATS metrics (e.g., message rates, consumer lag) with Laravel Telescope or Prometheus.

Operational Impact

Maintenance

  • Pros:
    • Single Binary: NATS server is lightweight (no Redis/RabbitMQ clustering).
    • JetStream Management: Streams/consumers can be managed via NATS CLI or Laravel commands.
    • Laravel Compatibility: Uses familiar patterns (e.g., service providers, queues).
  • Cons:
    • New Tooling: Team must learn NATS concepts (e.g., streams, consumers, JetStream).
    • Debugging: NATS logs may require additional tooling (e.g., nats-top, nats-sub).
  • Mitigation:
    • Document NATS-specific commands (e.g., php artisan nats:stream:list).
    • Use Laravel Telescope to log NATS events.

Support

  • Vendor Lock-in: NATS is open-source but lacks Laravel-specific support (
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony