Skip to main content

Quick start

Publish a message, receive it in a worker, and acknowledge that the work is complete. This walkthrough uses a local PostgreSQL database and your choice of Go, Rust, or TypeScript.

PostgreMQ runs inside PostgreSQL. You install its SQL schema and use a client library from your application; there is no separate message broker to start.

Before you start​

You need Docker, the PostgreSQL psql client, and one of these language environments:

LanguageRequirement
GoGo 1.25 or later
RustRust 1.94 or later
TypeScriptNode.js 22 or later

The examples use PostgreMQ SQL 0.1.1 and SDK 0.4.0 in each language. PostgreMQ requires PostgreSQL 15 or later.

Start PostgreSQL​

Start a database for this walkthrough:

docker run --name postgremq-quickstart \
-e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=postgremq_demo \
-p 127.0.0.1:55432:5432 \
-d postgres:15

export DATABASE_URL='postgres://postgres:postgres@localhost:55432/postgremq_demo?sslmode=disable'

Wait until this command reports that the database is accepting connections:

docker exec postgremq-quickstart pg_isready -U postgres -d postgremq_demo

These credentials and the unencrypted connection are for the local walkthrough.

Install PostgreMQ​

Download and apply the SQL for a fresh installation:

curl -fL \
https://github.com/postgremq/postgremq/releases/download/mq/v0.1.1/postgremq-v0.1.1.sql \
-o postgremq-v0.1.1.sql

psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f postgremq-v0.1.1.sql

The script creates the postgremq schema. Use migrations for an existing installation; see Upgrading PostgreMQ.

Send and receive a message​

Choose one language. Each program does the same five things:

  1. Connect to the database.
  2. Create the events topic and its quickstart-worker queue.
  3. Publish a JSON message.
  4. Receive and acknowledge one message.
  5. Close the connection.

Create the queue before publishing. A topic sends each new message to the queues subscribed at publication time; a queue created later does not receive earlier events.

Create a project:

mkdir postgremq-go-demo
cd postgremq-go-demo
go mod init example.com/postgremq-demo
go get postgremq.dev/postgremq-go@v0.4.0

Save this as main.go:

package main

import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"time"

"github.com/jackc/pgx/v5/pgxpool"
"postgremq.dev/postgremq-go"
)

func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}

func run() error {
ctx := context.Background()
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
return err
}
conn, err := postgremq.Dial(ctx, cfg,
postgremq.WithShutdownTimeout(5*time.Second))
if err != nil {
return err
}
defer conn.Close()

if err := conn.CreateTopic(ctx, "events"); err != nil {
return err
}
if err := conn.CreateQueue(ctx, "quickstart-worker", "events", false,
postgremq.WithMaxDeliveryAttempts(5)); err != nil {
return err
}

id, err := conn.Publish(ctx, "events",
json.RawMessage(`{"number":1}`))
if err != nil {
return err
}
fmt.Printf("Published message %d\n", id)

consumer, err := conn.Consume("quickstart-worker",
postgremq.WithBatchSize(1), postgremq.WithVT(30))
if err != nil {
return err
}
select {
case msg, ok := <-consumer.Messages():
if !ok {
return fmt.Errorf("consumer stopped before receiving a message")
}
fmt.Printf("Received message %d: %s\n", msg.ID, msg.Payload)
if err := msg.Ack(ctx); err != nil {
return err
}
fmt.Println("Acknowledged")
case <-time.After(10 * time.Second):
return fmt.Errorf("no message received within 10 seconds")
}
return nil
}

Run it:

go run .

On a fresh database, the output will look like this; JSON formatting varies by language:

Published message 1
Received message 1: {"number":1}
Acknowledged

The ID is assigned by PostgreMQ and may be different on your database. Each run publishes another message. Repeating declarations with the same settings is safe.

Check the result​

To inspect from an SDK, run the matching snippet while its connection is still open, before the program closes it. SQL can be run separately through psql "$DATABASE_URL".

queue := "quickstart-worker"
stats, err := conn.GetQueueStatistics(ctx, &queue)
if err != nil { return err }
fmt.Printf("pending=%d processing=%d completed=%d\n",
stats.PendingCount, stats.ProcessingCount, stats.CompletedCount)

After one successful run, expect zero pending messages, zero processing messages, and one completed message. Acknowledgement completes this queue's delivery; it does not immediately remove all stored data.

If a worker stops before acknowledging, PostgreMQ can deliver the message again after its visibility timeout. That is how unfinished work is recovered, and why real handlers must tolerate duplicates. This example allows five delivery attempts; normal operation also requires scheduled maintenance to retire abandoned final attempts and clean up completed work.

Take the next step​

  • Use Durable queues for a shared backlog or independent subscriptions that survive disconnects.
  • Use Exclusive queues for subscriptions that expire after their application goes away.
  • Read Consuming messages for handler consumers, acknowledgements, retries, and concurrency.
  • Use Transactional outbox to save application data and publish its event atomically.
  • Read Publishing messages for payloads, delays, ordering, and publication failures.

Before running a service in production, use a restricted runtime role, schedule postgremq.pmq_maintenance_fast() and bounded retention cleanup, monitor delivery progress, and configure graceful shutdown. Use Roles and permissions, Maintenance, and Monitoring to complete that production setup.

When you have finished with this walkthrough, remove its local database:

docker rm -f postgremq-quickstart

This removes all data in that container. It does not affect another PostgreSQL installation.