Examples

Each example publishes three messages and works them off. The second one fails on its first attempt, so you see the queue bring it back. Every example runs against a real server in the repository's test suite (examples/test.sh), so what you see here works.

All of them read LESSORMQ_URL and LESSORMQ_KEY (a key with the publish and consume scopes) and use the queue examples. With the queue's default backoff the failed message comes back after 10 seconds; set "backoff": {"initial_seconds": 0} on the queue to see it at once.

curl

The protocol by hand: publish, claim, fail, claim again, ack.

#!/usr/bin/env bash
# The whole protocol with curl: publish, claim, fail, claim again, ack.
# Needs LESSORMQ_URL and LESSORMQ_KEY (a key with the publish and consume scopes).
set -euo pipefail

url=${LESSORMQ_URL:-http://127.0.0.1:18080}
queue=${LESSORMQ_QUEUE:-examples}
auth="Authorization: Bearer $LESSORMQ_KEY"
json="Content-Type: application/json"

# Publish
curl -sS -X POST "$url/v1/queues/$queue/messages" -H "$auth" -H "$json" \
  -d '{"body": {"to": "ada@example.com"}, "dedup_key": "welcome-ada"}' | jq .

# Claim, waiting up to 5 seconds for a message
lease=$(curl -sS -X POST "$url/v1/queues/$queue/claims" -H "$auth" -H "$json" \
  -d '{"consumer": "curl", "wait_seconds": 5}')
echo "$lease" | jq .
id=$(echo "$lease" | jq -r .message.id)
receipt=$(echo "$lease" | jq -r .receipt)

# The job failed: report it, and let the queue decide what happens next
curl -sS -X POST "$url/v1/messages/$id/fail" -H "$auth" -H "$json" \
  -d "{\"receipt\": \"$receipt\", \"error\": {\"type\": \"SmtpTimeout\", \"message\": \"mail server did not answer\"}}" | jq .

# Claim again once the backoff has passed, and report success this time
sleep "${BACKOFF_WAIT:-11}"
lease=$(curl -sS -X POST "$url/v1/queues/$queue/claims" -H "$auth" -H "$json" -d '{"wait_seconds": 5}')
echo "$lease" | jq '{receipt, attempt: .message.attempt}'
curl -sS -o /dev/null -w "ack: %{http_code}\n" -X POST "$url/v1/messages/$(echo "$lease" | jq -r .message.id)/ack" \
  -H "$auth" -H "$json" -d "{\"receipt\": \"$(echo "$lease" | jq -r .receipt)\"}"

examples/curl/quickstart.sh

PHP

With the PHP library (composer require lessormq/client). The worker acks when the handler returns and fails when it throws; it extends the lease on its own while a long handler runs.

<?php

// Publish three messages and work them off with the LessorMQ worker.
// LESSORMQ_URL and LESSORMQ_KEY (publish and consume scopes); composer install first.

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use LessorMQ\Client;
use LessorMQ\Job;
use LessorMQ\Message;
use LessorMQ\Worker;
use LessorMQ\WorkerOptions;

$client = new Client(getenv('LESSORMQ_URL') ?: 'http://127.0.0.1:18080', getenv('LESSORMQ_KEY'));
$queue = getenv('LESSORMQ_QUEUE') ?: 'examples';

foreach ([['n' => 1], ['n' => 2, 'fail_once' => true], ['n' => 3]] as $body) {
    printf("published %s\n", $client->publish($queue, $body)->id);
}

$handled = 0;
$worker = null;
$worker = new Worker($client, $queue, function (Message $message, Job $job) use (&$handled, &$worker): void {
    $n = $message->body['n'];

    if (($message->body['fail_once'] ?? false) && $message->attempt === 1) {
        printf("n=%d attempt=%d failed\n", $n, $message->attempt);
        throw new RuntimeException('temporarily unavailable');
    }

    printf("n=%d attempt=%d handled\n", $n, $message->attempt);

    if (++$handled === 3) {
        $worker->stop();
    }
}, new WorkerOptions(consumer: 'php-example', waitSeconds: 5, maxSeconds: 60));

$worker->run();
printf("done: %d handled\n", $handled);
exit($handled === 3 ? 0 : 1);

examples/php/worker.php

Symfony Messenger

With the Messenger transport (composer require lessormq/messenger), your existing handlers run unchanged. Leave retries to the queue:

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            mail:
                dsn: 'lessormq://%env(LESSORMQ_KEY)%@mq.example.com/mail'
                options:
                    wait_seconds: 5
                retry_strategy:
                    max_retries: 0
        routing:
            App\Message\SendWelcomeMail: mail
use LessorMQ\Messenger\DedupKeyStamp;

// One open message per user, however often this runs
$bus->dispatch(new SendWelcomeMail($user->id), [new DedupKeyStamp('welcome-' . $user->id)]);

Throw UnrecoverableMessageHandlingException for input that can never succeed; any other exception is a failed attempt, and the queue decides what follows. Run messenger:consume mail --keepalive for handlers that take longer than the lease.

Python

The protocol over HTTP with requests, until the Python library is out.

"""Publish three messages and work them off, speaking the LessorMQ protocol directly.

Until the Python library is out, this is the protocol by hand (docs/protocol.md):
claim with a wait, run the job, then ack or fail with the receipt. The queue decides
what happens after a failure. Needs `requests`, LESSORMQ_URL and LESSORMQ_KEY.
"""
import os
import sys

import requests

URL = os.environ.get("LESSORMQ_URL", "http://127.0.0.1:18080").rstrip("/")
QUEUE = os.environ.get("LESSORMQ_QUEUE", "examples")
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["LESSORMQ_KEY"]


def call(method, path, body=None):
    response = session.request(method, URL + path, json=body if body is not None else {}, timeout=30)
    if response.status_code >= 400:
        problem = response.json()
        raise RuntimeError(f"{problem['code']}: {problem.get('detail', '')}")
    return response.json() if response.content else None


def publish(body):
    return call("POST", f"/v1/queues/{QUEUE}/messages", {"body": body})


def claim(wait_seconds=5):
    return call("POST", f"/v1/queues/{QUEUE}/claims", {"consumer": "python-example", "wait_seconds": wait_seconds})


def handle(message):
    body = message["body"]
    if body.get("fail_once") and message["attempt"] == 1:
        raise RuntimeError("temporarily unavailable")


for body in ({"n": 1}, {"n": 2, "fail_once": True}, {"n": 3}):
    print("published", publish(body)["id"])

handled = 0
while handled < 3:
    lease = claim()
    if lease is None:
        break
    message, receipt = lease["message"], lease["receipt"]
    try:
        handle(message)
    except Exception as error:
        result = call("POST", f"/v1/messages/{message['id']}/fail", {
            "receipt": receipt,
            "error": {"type": type(error).__name__, "message": str(error)},
        })
        print(f"n={message['body']['n']} attempt={message['attempt']} failed: {result['outcome']}")
        continue
    call("POST", f"/v1/messages/{message['id']}/ack", {"receipt": receipt})
    print(f"n={message['body']['n']} attempt={message['attempt']} handled")
    handled += 1

print(f"done: {handled} handled")
sys.exit(0 if handled == 3 else 1)

examples/python/worker.py

TypeScript

The protocol over fetch, until the TypeScript library is out. Runs on Node 22.6+ (node worker.ts), Bun and Deno.

// Publish three messages and work them off, speaking the LessorMQ protocol directly.
// Until the TypeScript library is out, this is the protocol by hand (docs/protocol.md).
// Runs on Node 22.6+ (`node worker.ts`), Bun and Deno. LESSORMQ_URL and LESSORMQ_KEY.

const url = (process.env.LESSORMQ_URL ?? "http://127.0.0.1:18080").replace(/\/$/, "");
const queue = process.env.LESSORMQ_QUEUE ?? "examples";
const key = process.env.LESSORMQ_KEY!;

interface Message { id: string; body: { n: number; fail_once?: boolean }; attempt: number; max_attempts: number }
interface Lease { receipt: string; lease_until: string; message: Message }

async function call<T>(path: string, body: unknown = {}): Promise<T | null> {
  const response = await fetch(url + path, {
    method: "POST",
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (response.status >= 400) {
    const problem = await response.json();
    throw new Error(`${problem.code}: ${problem.detail ?? ""}`);
  }
  return response.status === 204 ? null : (await response.json()) as T;
}

async function handle(message: Message): Promise<void> {
  if (message.body.fail_once && message.attempt === 1) {
    throw new Error("temporarily unavailable");
  }
}

for (const body of [{ n: 1 }, { n: 2, fail_once: true }, { n: 3 }]) {
  const published = await call<{ id: string }>(`/v1/queues/${queue}/messages`, { body });
  console.log("published", published!.id);
}

let handled = 0;
while (handled < 3) {
  const lease = await call<Lease>(`/v1/queues/${queue}/claims`, { consumer: "ts-example", wait_seconds: 5 });
  if (lease === null) break;
  const { message, receipt } = lease;
  try {
    await handle(message);
  } catch (error) {
    const result = await call<{ outcome: string }>(`/v1/messages/${message.id}/fail`, {
      receipt,
      error: { type: (error as Error).name, message: (error as Error).message },
    });
    console.log(`n=${message.body.n} attempt=${message.attempt} failed: ${result!.outcome}`);
    continue;
  }
  await call(`/v1/messages/${message.id}/ack`, { receipt });
  console.log(`n=${message.body.n} attempt=${message.attempt} handled`);
  handled++;
}

console.log(`done: ${handled} handled`);
process.exit(handled === 3 ? 0 : 1);

examples/typescript/worker.ts

Go

The protocol over net/http, until the Go library is out.

// Publish three messages and work them off, speaking the LessorMQ protocol directly.
// Until the Go library is out, this is the protocol by hand (docs/protocol.md).
// LESSORMQ_URL and LESSORMQ_KEY; go run .
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"
)

type message struct {
	ID      string `json:"id"`
	Attempt int    `json:"attempt"`
	Body    struct {
		N        int  `json:"n"`
		FailOnce bool `json:"fail_once"`
	} `json:"body"`
}

type lease struct {
	Receipt string  `json:"receipt"`
	Message message `json:"message"`
}

var (
	baseURL = strings.TrimSuffix(getenv("LESSORMQ_URL", "http://127.0.0.1:18080"), "/")
	queue   = getenv("LESSORMQ_QUEUE", "examples")
	client  = &http.Client{Timeout: 30 * time.Second}
)

func getenv(name, fallback string) string {
	if value := os.Getenv(name); value != "" {
		return value
	}
	return fallback
}

// call POSTs a JSON body and decodes the answer into out; it reports false on 204.
func call(path string, body any, out any) (bool, error) {
	payload, _ := json.Marshal(body)
	request, _ := http.NewRequest(http.MethodPost, baseURL+path, bytes.NewReader(payload))
	request.Header.Set("Authorization", "Bearer "+os.Getenv("LESSORMQ_KEY"))
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		return false, err
	}
	defer response.Body.Close()
	if response.StatusCode >= 400 {
		var problem struct{ Code, Detail string }
		json.NewDecoder(response.Body).Decode(&problem)
		return false, fmt.Errorf("%s: %s", problem.Code, problem.Detail)
	}
	if response.StatusCode == http.StatusNoContent || out == nil {
		return response.StatusCode != http.StatusNoContent, nil
	}
	return true, json.NewDecoder(response.Body).Decode(out)
}

func handle(m message) error {
	if m.Body.FailOnce && m.Attempt == 1 {
		return errors.New("temporarily unavailable")
	}
	return nil
}

func main() {
	for _, body := range []map[string]any{{"n": 1}, {"n": 2, "fail_once": true}, {"n": 3}} {
		var published struct{ ID string }
		if _, err := call("/v1/queues/"+queue+"/messages", map[string]any{"body": body}, &published); err != nil {
			panic(err)
		}
		fmt.Println("published", published.ID)
	}

	handled := 0
	for handled < 3 {
		var l lease
		got, err := call("/v1/queues/"+queue+"/claims", map[string]any{"consumer": "go-example", "wait_seconds": 5}, &l)
		if err != nil {
			panic(err)
		}
		if !got {
			break
		}
		if err := handle(l.Message); err != nil {
			var result struct{ Outcome string }
			report := map[string]any{"receipt": l.Receipt, "error": map[string]string{"type": "error", "message": err.Error()}}
			if _, err := call("/v1/messages/"+l.Message.ID+"/fail", report, &result); err != nil {
				panic(err)
			}
			fmt.Printf("n=%d attempt=%d failed: %s\n", l.Message.Body.N, l.Message.Attempt, result.Outcome)
			continue
		}
		if _, err := call("/v1/messages/"+l.Message.ID+"/ack", map[string]string{"receipt": l.Receipt}, nil); err != nil {
			panic(err)
		}
		fmt.Printf("n=%d attempt=%d handled\n", l.Message.Body.N, l.Message.Attempt)
		handled++
	}

	fmt.Printf("done: %d handled\n", handled)
	if handled != 3 {
		os.Exit(1)
	}
}

examples/go/main.go