Backend development

PHP and PostgreSQL: Advanced Queue Processing and LISTEN/NOTIFY for Event-Driven Architecture

Ruslan Ismailov Published 12 min read
P

Introduction: Why LISTEN/NOTIFY Instead of Polling or Redis?

In the world of event-driven architecture, PHP developers traditionally reach for Redis Pub/Sub, RabbitMQ, or Kafka — often overlooking the fact that PostgreSQL ships with a powerful built-in asynchronous notification mechanism: LISTEN/NOTIFY. If your system already uses PostgreSQL as its primary database, adding a separate message broker just for "event-driven" behavior introduces unnecessary infrastructure overhead.

Classic polling looks like this: a PHP worker executes SELECT * FROM jobs WHERE status = 'pending' every N seconds, processes rows, and goes back to sleep. It works, but it generates constant load on the database even when there are no events, increases latency, and pollutes logs. LISTEN/NOTIFY solves the problem in a fundamentally different way: PostgreSQL itself "wakes up" the subscriber when something happens. The connection stays in a waiting state and consumes no CPU — neither on the PHP side nor on the database side.

Redis Pub/Sub is faster and easier to scale horizontally, but it offers no transactional guarantees — notifications are sent immediately, outside of any transaction, and if the transaction rolls back, Redis has no way of knowing. PostgreSQL NOTIFY inside a transaction is only delivered upon a successful COMMIT — a critical advantage for data consistency.

How LISTEN/NOTIFY Works Internally

PostgreSQL implements NOTIFY through shared memory across server processes. When a backend process executes NOTIFY channel, 'payload', it writes the notification into a special pg_notify structure in shared memory. After the transaction completes (or immediately if called outside a transaction), the server iterates over all connections subscribed to that channel via LISTEN channel and sends each one an asynchronous signal.

Several key limitations to be aware of:

  • Payload is limited to 8,000 bytes — you cannot pass large JSON objects directly. Best practice is to send only the record ID and read the actual data from the table.
  • Notifications are not persistent — if a subscriber is disconnected at the moment of NOTIFY, it will not receive the message. This matters for delivery guarantees.
  • Deduplication — if a single transaction calls NOTIFY multiple times on the same channel with the same payload, the subscriber receives only one notification.
  • Channels are strings — channel names are case-sensitive, with a maximum length matching PostgreSQL identifier limits (63 bytes).

The pg_notify(channel, payload) function is the SQL equivalent of the NOTIFY command and is convenient for use inside trigger functions:

-- Direct NOTIFY call
NOTIFY order_created, '{"order_id": 42}';

-- Via function (convenient inside triggers)
SELECT pg_notify('order_created', json_build_object('order_id', NEW.id)::text);

PHP Implementation: PDO and ext-pgsql

Unfortunately, standard PDO does not provide a native API for receiving asynchronous notifications from PostgreSQL. To work with LISTEN/NOTIFY in PHP, you need to use the ext-pgsql extension (the pg_* family of functions). It provides the pg_get_notify() function and supports asynchronous mode via pg_socket().

Here is a basic example of a PHP worker that subscribes to a channel and processes notifications:

<?php

declare(strict_types=1);

$dsn = 'host=127.0.0.1 port=5432 dbname=myapp user=worker password=secret';
$conn = pg_connect($dsn);

if (!$conn) {
    throw new RuntimeException('Failed to connect to PostgreSQL');
}

// Subscribe to channels
pg_query($conn, 'LISTEN order_created');
pg_query($conn, 'LISTEN payment_processed');

echo "Worker started, waiting for notifications...\n";

// Get the socket file descriptor for select()
$socket = pg_socket($conn);

while (true) {
    // Use stream_select to wait for data without busy-looping
    $read   = [$socket];
    $write  = null;
    $except = null;

    $changed = stream_select($read, $write, $except, 10); // 10-second timeout

    if ($changed === false) {
        // select() error — reconnect
        break;
    }

    // Consume incoming data from the socket
    if (!pg_consume_input($conn)) {
        throw new RuntimeException('pg_consume_input failed: ' . pg_last_error($conn));
    }

    // Read all accumulated notifications
    while ($notify = pg_get_notify($conn, PGSQL_ASSOC)) {
        $channel = $notify['message'];   // channel name
        $payload = $notify['extra'];     // payload string
        $pid     = $notify['be_pid'];    // PID of the sending process

        echo "Received on [{$channel}] from PID {$pid}: {$payload}\n";

        handleNotification($channel, $payload);
    }
}

pg_close($conn);

function handleNotification(string $channel, string $payload): void
{
    $data = json_decode($payload, true);

    match ($channel) {
        'order_created'     => processNewOrder($data),
        'payment_processed' => processPayment($data),
        default             => throw new UnexpectedValueException("Unknown channel: {$channel}"),
    };
}

function processNewOrder(array $data): void
{
    // Business logic for handling a new order
    echo "Processing order #{$data['order_id']}\n";
}

function processPayment(array $data): void
{
    echo "Processing payment #{$data['payment_id']}\n";
}

The key point: stream_select() blocks the thread until data arrives or the timeout expires. This is not a busy-loop — no CPU is spent waiting. The timeout is needed to periodically check the connection state (heartbeat) and handle process termination signals.

If you still want to use PDO, you can execute LISTEN through PDO and open a second connection via ext-pgsql for receiving notifications — not the most elegant solution, but it works for projects with an established PDO infrastructure.

Building a Lightweight Event-Driven Queue with Delivery Guarantees

As mentioned above, NOTIFY is not persistent. If a worker crashes at the moment of an event, the event is lost. The solution is a hybrid approach: a queue table combined with NOTIFY as a signal to "check the queue."

Create a table to store jobs:

CREATE TABLE job_queue (
    id          BIGSERIAL PRIMARY KEY,
    channel     TEXT NOT NULL,
    payload     JSONB NOT NULL,
    status      TEXT NOT NULL DEFAULT 'pending',  -- pending, processing, done, failed
    attempts    INT NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    locked_at   TIMESTAMPTZ,
    locked_by   TEXT  -- worker identifier
);

CREATE INDEX ON job_queue (status, created_at) WHERE status = 'pending';

Now create a trigger that automatically sends a NOTIFY when a new job is inserted:

CREATE OR REPLACE FUNCTION notify_job_queue()
RETURNS TRIGGER AS $$
BEGIN
    -- Send only the job ID — lightweight payload, actual data is in the table
    PERFORM pg_notify('job_queue', NEW.id::text);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_notify_job_queue
AFTER INSERT ON job_queue
FOR EACH ROW EXECUTE FUNCTION notify_job_queue();

PHP worker with delivery guarantees using SELECT FOR UPDATE SKIP LOCKED:

<?php

function fetchAndLockJob(PgSql\Connection $conn, string $workerId): ?array
{
    pg_query($conn, 'BEGIN');

    $result = pg_query_params(
        $conn,
        'SELECT id, channel, payload
         FROM job_queue
         WHERE status = $1
         ORDER BY created_at
         LIMIT 1
         FOR UPDATE SKIP LOCKED',
        ['pending']
    );

    $row = pg_fetch_assoc($result);

    if (!$row) {
        pg_query($conn, 'ROLLBACK');
        return null;
    }

    // Mark the job as "in progress"
    pg_query_params(
        $conn,
        'UPDATE job_queue
         SET status = $1, locked_at = now(), locked_by = $2, attempts = attempts + 1
         WHERE id = $3',
        ['processing', $workerId, $row['id']]
    );

    pg_query($conn, 'COMMIT');

    $row['payload'] = json_decode($row['payload'], true);
    return $row;
}

function markJobDone(PgSql\Connection $conn, int $jobId): void
{
    pg_query_params(
        $conn,
        'UPDATE job_queue SET status = $1 WHERE id = $2',
        ['done', $jobId]
    );
}

function markJobFailed(PgSql\Connection $conn, int $jobId): void
{
    pg_query_params(
        $conn,
        "UPDATE job_queue SET status = CASE WHEN attempts >= 3 THEN 'failed' ELSE 'pending' END WHERE id = $1",
        [$jobId]
    );
}

SELECT FOR UPDATE SKIP LOCKED is the key pattern for concurrent processing. Multiple workers can safely pull jobs in parallel: each gets a unique row, and all other locked rows are skipped without blocking.

Practical Patterns: Fan-Out, Filtering, and Multiple Subscribers

Event Fan-Out

When a single event must be handled by multiple independent subsystems (e.g., order created → notify warehouse, billing, and email service), use multiple channels or insert multiple rows into job_queue with different channel values:

-- On order creation, insert jobs for all subsystems
INSERT INTO job_queue (channel, payload) VALUES
    ('warehouse.order_created',     '{"order_id": 123}'),
    ('billing.order_created',       '{"order_id": 123}'),
    ('notifications.order_created', '{"order_id": 123}');
-- The trigger automatically sends NOTIFY for each row

Channel Filtering

Workers can subscribe to specific channels. Use pattern-based channels through naming conventions: wildcard subscriptions like warehouse.* are not natively supported, but you can subscribe a warehouse worker to warehouse_jobs and filter the event type via the channel field in the table.

Multiple Workers on a Single Channel

When scaling horizontally, all workers receive the same NOTIFY message — that's fine, because SELECT FOR UPDATE SKIP LOCKED ensures that only one worker actually claims and processes the job. The others simply find no available rows.

Comparison with Redis Pub/Sub and Kafka

Tool selection depends on your system's requirements. Here are the key comparative characteristics:

  • PostgreSQL LISTEN/NOTIFY: transactional (NOTIFY only on COMMIT), no native notification persistence (requires a queue table), limited payload (8 KB), no additional infrastructure needed, ideal for monoliths and services already running on PostgreSQL.
  • Redis Pub/Sub: very high throughput (hundreds of thousands of messages/sec), no transactionality, no persistence (unless using Streams), requires a separate Redis service, great for real-time notifications where message loss is acceptable.
  • Kafka: maximum reliability and scalability, persistence, event replay, partitioning — but high operational complexity, requires JVM infrastructure, overkill for small and medium workloads.

Rule of thumb: if you already have PostgreSQL and your load doesn't exceed a few thousand events per minute, LISTEN/NOTIFY with a queue table will fully cover your needs without extra dependencies.

Scaling and Limitations: PgBouncer and Connection Pooling

This is where the main production pitfall lies. PgBouncer in transaction pooling mode is incompatible with LISTEN/NOTIFY. The reason: LISTEN is state tied to a specific server connection. In transaction mode, PgBouncer reuses connections between transactions, meaning "your" connection may be handed to another client at the moment a notification arrives.

Workarounds:

  • Session pooling in PgBouncer — each client holds a dedicated server connection. Less efficient in terms of connection count, but compatible with LISTEN.
  • Direct connections for workers — allocate a separate connection pool (or direct connections bypassing PgBouncer) specifically for workers using LISTEN. This is standard practice: web traffic goes through PgBouncer, while a small number of workers connect directly.
  • pgmq / SKIP LOCKED without LISTEN — if scaling is critical, you can drop LISTEN/NOTIFY entirely and use polling with SELECT FOR UPDATE SKIP LOCKED at a short interval (e.g., 100–500 ms). Latency loss is minimal, and PgBouncer works normally.

Also keep in mind the limit on simultaneous PostgreSQL connections. Each LISTEN worker holds a persistent connection. For 10–20 workers this is negligible; for 1,000, it becomes a problem. In that case, the architecture should include an aggregator process (one process listens to PostgreSQL and distributes jobs to workers via an internal queue, such as SplQueue or channels in ReactPHP/Swoole).

Testing and Monitoring

Testing

For unit-testing handler business logic, mock the dispatcher function — no real PostgreSQL connection is needed to verify that an order is processed correctly. For integration tests, use a real PostgreSQL instance in Docker:

# docker-compose.test.yml
services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: testdb
      POSTGRES_USER: test
      POSTGRES_PASSWORD: test
    ports:
      - "5433:5432"

In integration tests (PHPUnit), launch the worker in a separate process via proc_open(), INSERT into the job table, and verify the result after a few seconds. An alternative is to test the fetchAndLockJob() method directly, without real LISTEN.

Monitoring

Useful SQL queries for monitoring system state:

-- Job counts by status
SELECT status, COUNT(*) FROM job_queue GROUP BY status;

-- Stuck jobs (processing for more than 10 minutes)
SELECT id, channel, locked_by, locked_at
FROM job_queue
WHERE status = 'processing'
  AND locked_at < now() - INTERVAL '10 minutes';

-- Current LISTEN subscribers
SELECT pid, usename, application_name, client_addr
FROM pg_stat_activity
WHERE wait_event_type = 'Client'
  AND wait_event = 'ClientRead';

-- Active channels and subscriber counts
SELECT channel, COUNT(*) as subscribers
FROM pg_listening_channels() -- for the current connection only
GROUP BY channel;

Add Prometheus metrics to your worker (e.g., using the promphp/prometheus_client_php library): a counter for processed jobs, a gauge for queue statuses, and a processing latency histogram. Alerts for queue growth in pending status and stuck jobs in processing are mandatory for production.

It also makes sense to log the PostgreSQL process PID that sent the notification ($notify['be_pid']) — this helps debug situations where it's unclear who triggered an event.

Conclusion

PHP and PostgreSQL together provide a powerful, transactionally safe event-driven processing mechanism without introducing additional message brokers. The LISTEN/NOTIFY mechanism is ideal for teams that want system reactivity with minimal operational complexity.

Key takeaways from this article:

  • Use NOTIFY only as a signal that "new data is available," and store the actual data in a queue table with SELECT FOR UPDATE SKIP LOCKED for reliability and concurrent processing.
  • To receive notifications in PHP, use ext-pgsql with stream_select() — this is more efficient than polling and requires no busy-loop.
  • NOTIFY inside a transaction guarantees that the subscriber learns about the event only after a successful COMMIT — a fundamental advantage over Redis Pub/Sub for consistent systems.
  • Work around PgBouncer incompatibility by using direct connections for workers or switching to session pooling.
  • Monitor queue size, stuck jobs, and latency — these are the foundation of a reliable event-driven system on PostgreSQL.

For workloads exceeding a few thousand events per second, or when replay semantics are required, consider migrating to Kafka or using the pgmq extension. But for the vast majority of PHP applications, PostgreSQL LISTEN/NOTIFY is a sufficient, elegant, and underappreciated tool.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →