$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[April 21, 2024] PostgreSQL

PostgreSQL LISTEN/NOTIFY: Real-Time Events

PostgreSQL LISTEN/NOTIFY: Real-Time Events

────────────────────────────────────────────────────────

PostgreSQL LISTEN/NOTIFY: Real-Time Events

Tip: Basic NOTIFY

NOTIFY channel_name, 'payload data';

Sends a notification to all listeners on the channel.

Gotcha: Payload Limited to 8000 Bytes

For large payloads, send an ID and let the listener fetch the full data.

Tip: LISTEN in PHP

$db->exec("LISTEN orders");
while (true) {
    $db->poll();
    $notifications = $db->getNotify();
    foreach ($notifications as $n) {
        process($n);
    }
}

Gotcha: LISTEN Blocks the Connection

A listening connection can't run other queries. Use a dedicated connection.

Tip: Conditional Notifications with Triggers

CREATE OR REPLACE FUNCTION notify_order() RETURNS trigger AS $$
BEGIN
    PERFORM pg_notify('order_events', row_to_json(NEW)::text);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER order_notify AFTER INSERT ON orders
    FOR EACH ROW EXECUTE FUNCTION notify_order();

Gotcha: Notifications Are Not Persistent

If no one is listening, the notification is lost. Not a replacement for a message queue.

Tip: EXPLAIN (ANALYZE, BUFFERS) Is Your Best Friend

For query debugging, always use EXPLAIN (ANALYZE, BUFFERS) instead of plain EXPLAIN. The BUFFERS option shows hit/miss rates for every node, revealing whether your indexes are actually in memory.

Tip: Partial Indexes Are Underutilized

CREATE INDEX ON orders (status) WHERE status = 'pending' creates a tiny index that covers only the rows your query needs. It's faster to scan and cheaper to maintain than a full-column index.

Gotcha: NULL Sorting Is Non-Obvious

By default, NULLs sort AFTER non-null values in ascending order. ORDER BY col DESC puts NULLs FIRST. Use NULLS LAST or NULLS FIRST to be explicit.

Senior Insight

PostgreSQL is the database I recommend for most Laravel applications. Its feature set, reliability, and performance characteristics make it suitable for everything from small blogs to enterprise applications. The investment in learning PostgreSQL deeply — beyond basic CRUD — pays dividends as your application grows. Understanding indexing strategies, query planning, and connection management separates developers who build robust applications from those who fight database fires.

Source: pganalyze Blog (https://pganalyze.com/blog), PostgreSQL Docs (https://www.postgresql.org/docs/current/), Crunchy Data Blog (https://www.crunchydata.com/blog)

────────────────────────────────────────────────────────
<-- back to posts