Events
An orders API with @dotpress/events, on Fastify. Placing an order emits an order.placed event; its two listeners run later, in a worker, through a Redis queue (BullMQ):
- the API answers without waiting for the listeners: it only queues one message per listener;
send-order-confirmationlogs the confirmation, andnotify-warehousecalls a warehouse service over HTTP, with an idempotency key;- a listener that throws is retried (3 attempts, exponential backoff), then kept in the failed jobs of the queue;
- without Redis, an in-memory queue runs the listeners in the API process: nothing to install to try it.
Source: examples/events.
Run it
The logs of the API show the listeners running.
With Redis
Stop the worker, place orders, then start it again: it handles the orders that waited in the queue. npm run worker runs dotpress-events work src/worker.ts --watch.
The event and its listeners
Shared by the API and the worker. load imports the code of a listener in the worker only:
A listener can run twice: the message id is the idempotency key sent to the warehouse service.
Emitting
The route stores the order, then emits: an event describes something that happened.
The transport comes from the configuration: BullMQ with REDIS_URL, an in-memory queue without it.
The worker
In production, run the API and the worker as two processes, with dotpress-events work src/worker.ts (without --watch). On SIGTERM, the worker finishes the jobs in progress before exiting.
Learn more
- Events and workers
- Deployment › Event workers: SQS, pg-boss, Cloudflare Queues, Pub/Sub, Service Bus
- Testing helpers