PHPackages                             offload-project/laravel-google-pubsub - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. offload-project/laravel-google-pubsub

ActiveLibrary[Queues &amp; Workers](/categories/queues)

offload-project/laravel-google-pubsub
=====================================

Google Cloud Pub/Sub for Laravel with full feature support

v1.1.0(1mo ago)84511MITPHPPHP ^8.3CI passing

Since Dec 16Pushed 1mo agoCompare

[ Source](https://github.com/offload-project/laravel-google-pubsub)[ Packagist](https://packagist.org/packages/offload-project/laravel-google-pubsub)[ Docs](https://github.com/offload-project/laravel-google-pubsub)[ RSS](/packages/offload-project-laravel-google-pubsub/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (20)Versions (6)Used By (1)

 [![Latest Version on Packagist](https://camo.githubusercontent.com/60e2626742aecfd9251f26f80f8c1a18a56b386ebf5305d61144b0ec663432a6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f66666c6f61642d70726f6a6563742f6c61726176656c2d676f6f676c652d7075627375622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/offload-project/laravel-google-pubsub) [![GitHub Tests Action Status](https://camo.githubusercontent.com/1922c0157bd6f08337759a29ca65ccace8d41c005114e901fea28661c43340a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f66666c6f61642d70726f6a6563742f6c61726176656c2d676f6f676c652d7075627375622f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265)](https://github.com/offload-project/laravel-google-pubsub/actions) [![Total Downloads](https://camo.githubusercontent.com/55ad58374e802a3aa93d53f59032ea926bf5a9f703a46e7d4ad55fdf884b945a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f66666c6f61642d70726f6a6563742f6c61726176656c2d676f6f676c652d7075627375622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/offload-project/laravel-google-pubsub)

Laravel Google Pub/Sub
======================

[](#laravel-google-pubsub)

A comprehensive Google Cloud Pub/Sub integration for Laravel that goes beyond basic queue functionality. This package provides a complete toolkit for building event-driven architectures, microservice communication, and real-time data pipelines.

Features
--------

[](#features)

- **Full Laravel Queue Driver** - Seamless integration with Laravel's queue system
- **Publisher/Subscriber Services** - Direct publishing with compression, metadata, and batch support
- **Event Integration** - Bidirectional event flow between Laravel and Pub/Sub
- **Webhook Support** - Handle push subscriptions with built-in security
- **Schema Validation** - JSON Schema validation for message contracts
- **Streaming Support** - Real-time message processing with StreamingPull
- **Multi-Service Architecture** - Built for microservice communication
- **CloudEvents Support** - Industry-standard event formatting with v1.0 compatibility
- **Enterprise Ready** - Dead letter topics, retry policies, monitoring
- **Emulator Support** - Local development with Google Cloud Pub/Sub emulator
- **Laravel Octane Compatible** - Optimized for high-performance applications
- **Comprehensive CLI** - Rich set of Artisan commands for management

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Basic Configuration](#basic-configuration)
- [Quick Start](#quick-start)
    - [Basic Queue Usage](#1-basic-queue-usage)
    - [Direct Publishing](#2-direct-publishing)
    - [Event Integration](#3-event-integration)
    - [Subscribing to Messages](#4-subscribing-to-messages)
- [Full Documentation](#full-documentation)
- [Performance Tips](#performance-tips)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

Requirements
------------

[](#requirements)

- PHP 8.4+
- Laravel 11.0+
- Google Cloud Pub/Sub PHP library

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require offload-project/laravel-google-pubsub
```

Publish the configuration file:

```
php artisan vendor:publish --provider="OffloadProject\GooglePubSub\PubSubServiceProvider" --tag="config"
```

Basic Configuration
-------------------

[](#basic-configuration)

### Environment Variables

[](#environment-variables)

Add the following to your `.env` file:

```
# Basic Configuration
QUEUE_CONNECTION=pubsub
GOOGLE_CLOUD_PROJECT_ID=your-project-id

# Authentication (choose one method)
# Method 1: Service Account Key File
PUBSUB_AUTH_METHOD=key_file
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

# Method 2: Application Default Credentials
PUBSUB_AUTH_METHOD=application_default

# Optional Settings
PUBSUB_DEFAULT_QUEUE=default
PUBSUB_AUTO_CREATE_TOPICS=true
PUBSUB_AUTO_CREATE_SUBSCRIPTIONS=true
```

### Queue Configuration

[](#queue-configuration)

Update your `config/queue.php`:

```
'connections' => [
    'pubsub' => [
        'driver' => 'pubsub',
        'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
        'queue' => env('PUBSUB_DEFAULT_QUEUE', 'default'),
        'auth_method' => env('PUBSUB_AUTH_METHOD', 'application_default'),
        'key_file' => env('GOOGLE_APPLICATION_CREDENTIALS'),

        // Optional overrides
        'auto_create_topics' => true,
        'auto_create_subscriptions' => true,
        'subscription_suffix' => '-laravel',
        'enable_message_ordering' => false,
    ],
],
```

Quick Start
-----------

[](#quick-start)

### 1. Basic Queue Usage

[](#1-basic-queue-usage)

Use it exactly like any other Laravel queue:

```
// Dispatch jobs as normal
ProcessPodcast::dispatch($podcast);

// Dispatch to specific queue (Pub/Sub topic)
ProcessPodcast::dispatch($podcast)->onQueue('audio-processing');

// Your Go microservices can subscribe to the same topic
// Subscription name: audio-processing-go-service
```

### 2. Direct Publishing

[](#2-direct-publishing)

```
use OffloadProject\GooglePubSub\Facades\PubSub;

// Publish directly to a topic
PubSub::publish('orders', [
    'order_id' => 123,
    'total' => 99.99,
    'customer_id' => 456
]);

// With attributes and ordering
PubSub::publish('orders', $data, [
    'priority' => 'high',
    'source' => 'api'
], [
    'ordering_key' => 'customer-456'
]);
```

### 3. Event Integration

[](#3-event-integration)

```
use OffloadProject\GooglePubSub\Attributes\PublishTo;
use OffloadProject\GooglePubSub\Contracts\ShouldPublishToPubSub;

#[PublishTo('orders')]
class OrderPlaced implements ShouldPublishToPubSub
{
    public function __construct(
        public Order $order
    ) {}

    public function pubsubTopic(): string
    {
        return 'orders';
    }

    public function toPubSub(): array
    {
        return [
            'order_id' => $this->order->id,
            'total' => $this->order->total,
            'customer_id' => $this->order->customer_id,
        ];
    }
}

// This event automatically publishes to the 'orders' topic
event(new OrderPlaced($order));
```

### 4. Subscribing to Messages

[](#4-subscribing-to-messages)

```
use OffloadProject\GooglePubSub\Facades\PubSub;

// Create a subscriber
$subscriber = PubSub::subscribe('orders-processor', 'orders');

// Add message handler
$subscriber->handler(function ($data, $message) {
    // Process the order
    processOrder($data);
});

// Start listening
$subscriber->listen();
```

Full Documentation
------------------

[](#full-documentation)

- [Installation](docs/implementation/installation.md)
- [Configuration](docs/implementation/configuration.md) (comprehensive)
- [Queue Driver](docs/queue-driver.md)
- [Publisher &amp; Subscriber](docs/direct-pubsub.md)
- [Event Integration](docs/event-integration.md)
- [Webhooks (Push Subscriptions)](docs/webhook-push.md)
- [Message Schemas and Validation](docs/messages/message-schemas.md)
- [CloudEvents](docs/messages/cloudevents.md)
- [Artisan Command](docs/artisan-commands.md)
- [Monitoring &amp; Debugging](docs/reference/monitoring-debugging.md)
- [Testing](docs/reference/testing.md)
- [Examples](docs/reference/examples.md)

Performance Tips
----------------

[](#performance-tips)

### 1. Use Streaming Subscribers for Real-time Processing

[](#1-use-streaming-subscribers-for-real-time-processing)

Streaming subscribers provide lower latency and better throughput:

```
// config/pubsub.php
'use_streaming' => true,

// Real-time processing
$subscriber = PubSub::subscribe('high-volume-subscription');
$subscriber->stream(['max_messages_per_pull' => 1000]);
```

### 2. Enable Message Ordering Only When Necessary

[](#2-enable-message-ordering-only-when-necessary)

Ordering reduces throughput, use it selectively:

```
// Only for specific topics that require order
'topics' => [
    'financial-transactions' => [
        'enable_message_ordering' => true,
    ],
    'analytics' => [
        'enable_message_ordering' => false, // Better performance
    ],
],
```

### 3. Set Appropriate Timeouts for Job Processing

[](#3-set-appropriate-timeouts-for-job-processing)

Match acknowledgment deadlines to your processing time:

```
// Quick jobs (< 30 seconds)
'subscriptions' => [
    'quick-jobs' => ['ack_deadline' => 30],
],

// Slow jobs (up to 10 minutes)
'subscriptions' => [
    'data-processing' => ['ack_deadline' => 600],
],
```

### 4. Monitor Dead Letter Topics for Failed Messages

[](#4-monitor-dead-letter-topics-for-failed-messages)

Set up automated monitoring:

```
# Check dead letter queue size
php artisan pubsub:dead-letters orders --summary

# Reprocess dead letters
php artisan pubsub:dead-letters orders --process
```

### 5. Use Compression for Large Payloads

[](#5-use-compression-for-large-payloads)

Automatic compression for messages over 1KB:

```
'message_options' => [
    'compress_payload' => true,
    'compression_threshold' => 1024, // bytes
],
```

### 6. Batch Publishing for High Volume

[](#6-batch-publishing-for-high-volume)

Reduce API calls with batch publishing:

```
$messages = collect($items)->map(fn($item) => [
    'data' => $item->toArray(),
    'attributes' => ['type' => 'bulk-import'],
]);

PubSub::publishBatch('imports', $messages->toArray());
```

### 7. Connection Pooling with Octane

[](#7-connection-pooling-with-octane)

Laravel Octane automatically reuses connections:

```
// config/octane.php
'warm' => [
    'pubsub', // Warm the Pub/Sub manager
],
```

Troubleshooting
---------------

[](#troubleshooting)

### Connection Errors

[](#connection-errors)

#### Verify your Google Cloud project ID

[](#verify-your-google-cloud-project-id)

```
# Check current project
gcloud config get-value project

# Verify in your .env
grep GOOGLE_CLOUD_PROJECT_ID .env
```

#### Check service account permissions

[](#check-service-account-permissions)

```
# List current service account permissions
gcloud projects get-iam-policy your-project-id \
  --flatten="bindings[].members" \
  --filter="bindings.members:serviceAccount:your-service-account@*.iam.gserviceaccount.com"

# Required roles:
# - roles/pubsub.publisher (to publish)
# - roles/pubsub.subscriber (to subscribe)
# - roles/pubsub.admin (to create topics/subscriptions)
```

#### Ensure Pub/Sub API is enabled

[](#ensure-pubsub-api-is-enabled)

```
# Check if API is enabled
gcloud services list --enabled | grep pubsub

# Enable if needed
gcloud services enable pubsub.googleapis.com
```

### Message Delivery Issues

[](#message-delivery-issues)

#### Check subscription acknowledgment settings

[](#check-subscription-acknowledgment-settings)

```
# View subscription details
gcloud pubsub subscriptions describe orders-laravel

# Update ack deadline if needed
gcloud pubsub subscriptions update orders-laravel --ack-deadline=120
```

#### Verify topic and subscription names

[](#verify-topic-and-subscription-names)

```
# List all topics
php artisan pubsub:topics:list

# List all subscriptions
php artisan pubsub:subscriptions:list

# Test specific subscription
php artisan pubsub:listen orders-laravel --max-messages=1
```

#### Monitor dead letter topics

[](#monitor-dead-letter-topics)

```
# Check if dead letter is configured
gcloud pubsub subscriptions describe orders-laravel \
  --format="value(deadLetterPolicy)"

# Monitor dead letter messages
php artisan pubsub:listen orders-dead-letter-inspector \
  --topic=orders-dead-letter \
  --max-messages=10
```

### Performance Issues

[](#performance-issues)

#### Adjust max\_messages and ack\_deadline settings

[](#adjust-max_messages-and-ack_deadline-settings)

```
// In config/queue.php or config/pubsub.php
'pubsub' => [
    'max_messages' => 100,        // Increase for batch processing
    'ack_deadline' => 120,        // Increase for slow jobs
    'wait_time' => 0,            // Reduce for lower latency
],
```

#### Use streaming subscribers for high throughput

[](#use-streaming-subscribers-for-high-throughput)

```
// For real-time, high-volume processing
$subscriber = PubSub::subscribe('high-volume');
$subscriber->stream([
    'max_messages_per_pull' => 1000,
]);
```

#### Consider message batching for publishing

[](#consider-message-batching-for-publishing)

```
// Instead of individual publishes
collect($events)->each(fn($e) => PubSub::publish('events', $e));

// Use batch publishing
$messages = collect($events)->map(fn($e) => ['data' => $e])->toArray();
PubSub::publishBatch('events', $messages);
```

### Memory Issues

[](#memory-issues)

#### Large Message Handling

[](#large-message-handling)

```
// Monitor memory usage
$subscriber->handler(function ($data, $message) {
    $before = memory_get_usage();

    // Process large message
    $this->processLargeFile($data);

    // Force garbage collection if needed
    if (memory_get_usage() - $before > 50 * 1024 * 1024) { // 50MB
        gc_collect_cycles();
    }
});
```

#### Queue Worker Memory Limits

[](#queue-worker-memory-limits)

```
# Set appropriate memory limit
php artisan queue:work pubsub --memory=512 --timeout=300
```

### Authentication Issues

[](#authentication-issues)

#### Application Default Credentials

[](#application-default-credentials)

```
# Set up ADC locally
gcloud auth application-default login

# Verify credentials
gcloud auth application-default print-access-token
```

#### Service Account Key File

[](#service-account-key-file)

```
# Verify key file exists and is valid
ls -la $GOOGLE_APPLICATION_CREDENTIALS

# Test authentication
php artisan pubsub:topics:list
```

### Debugging Tools

[](#debugging-tools)

#### Enable Debug Logging

[](#enable-debug-logging)

```
# In .env
PUBSUB_LOG_PUBLISHED=true
PUBSUB_LOG_CONSUMED=true
PUBSUB_LOG_FAILED=true
PUBSUB_LOG_WEBHOOKS=true
```

#### Message Inspector

[](#message-inspector)

```
# Inspect messages without processing
php artisan pubsub:inspect orders-laravel --limit=5
```

#### Test Publishing

[](#test-publishing)

```
# Test with a simple message
php artisan pubsub:publish orders '{"test":true,"timestamp":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}'
```

#### Health Check

[](#health-check)

```
# Run health check
curl http://your-app.com/health/pubsub
```

### Common Error Messages

[](#common-error-messages)

#### "Permission denied"

[](#permission-denied)

- Check service account has required Pub/Sub roles
- Verify project ID is correct
- Ensure API is enabled

#### "Resource not found"

[](#resource-not-found)

- Topic or subscription doesn't exist
- Enable auto-creation or create manually

#### "Deadline exceeded"

[](#deadline-exceeded)

- Increase ack\_deadline for slow processing jobs
- Consider breaking large jobs into smaller tasks

#### "Invalid message format"

[](#invalid-message-format)

- Check schema validation if enabled
- Verify JSON encoding of messages
- Check for compression issues with large payloads

Testing
-------

[](#testing)

```
./vendor/bin/pest
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance98

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 81.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~104 days

Total

2

Last Release

39d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/331bcc01f75f46dded875d74f3db055da6d74be5f8820f0a29105c6a2cd8afc8?d=identicon)[shavonn](/maintainers/shavonn)

---

Top Contributors

[![shavonn](https://avatars.githubusercontent.com/u/3074595?v=4)](https://github.com/shavonn "shavonn (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

laravelcloudgooglequeuepubsubgcp

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/offload-project-laravel-google-pubsub/health.svg)

```
[![Health](https://phpackages.com/badges/offload-project-laravel-google-pubsub/health.svg)](https://phpackages.com/packages/offload-project-laravel-google-pubsub)
```

###  Alternatives

[kainxspirits/laravel-pubsub-queue

Queue driver for Google Cloud Pub/Sub.

48381.1k3](/packages/kainxspirits-laravel-pubsub-queue)[nuwber/rabbitevents

The Nuwber RabbitEvents package

120515.8k3](/packages/nuwber-rabbitevents)[stackkit/laravel-google-cloud-tasks-queue

Google Cloud Tasks queue driver for Laravel

84570.1k](/packages/stackkit-laravel-google-cloud-tasks-queue)[pod-point/laravel-aws-pubsub

A Laravel broadcasting driver and queue driver that broadcasts and listens to published events utilising AWS SNS, EventBridge and SQS.

1096.1k](/packages/pod-point-laravel-aws-pubsub)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
