Skip to main content

Graceful shutdown

Graceful shutdown stops new queue work and gives in-progress deliveries time to finish before the application exits. Use it when deploying a new version, scaling workers down, or stopping a service for maintenance.

Configure a finite shutdown timeout and call the connection's close method from the part of your application that manages its lifecycle. Handlers remain responsible for acknowledging completed work and responding to cancellation.

The behavior below applies to SDK 0.4.0.

Configure a shutdown budget​

Choose a timeout that leaves room inside your deployment's termination budget for other cleanup. If the process will be killed after 30 seconds, the queue connection should not consume all 30 seconds by itself.

These examples allow up to 20 seconds for the queue shutdown wait. cfg in Go is the pgxpool.Config used in the Quick start.

conn, err := postgremq.Dial(ctx, cfg,
postgremq.WithShutdownTimeout(20*time.Second))
if err != nil {
return err
}

// Later, from the application's lifecycle code:
if err := conn.Close(); err != nil {
return err
}

Go and Rust wait indefinitely by default. TypeScript defaults to 30 seconds. Setting an explicit timeout makes your application's deployment behavior deliberate and visible in its configuration.

The timeout bounds waiting for queue work; it cannot forcibly stop your application code or make a driver or external resource ignore its own lifecycle. Leave time for final cleanup and make handlers cooperate with cancellation.

What happens when you close​

The connection performs the following sequence:

  1. Reject new work. New publishes, topic and queue declarations, and new consumers fail with the SDK's closed-connection error.
  2. Stop receiving. Consumers stop fetching and return buffered messages that have not reached application code, where database communication succeeds. Returning this unattempted work does not spend a delivery attempt.
  3. Ask active handlers to stop. Each active delivery's cancellation signal fires. Acknowledgements remain available during the drain, and automatic delivery extension continues while the connection waits.
  4. Finish or reach the deadline. Once the drain ends, background activity stops and a pool created by PostgreMQ is closed. A pool supplied by the application remains the application's responsibility.

Closing again is safe. A closed connection is not reused for new work; create a new connection if the application needs to resume.

Decide what your handler should do​

Cancellation is a request to cooperate, not a rollback of completed effects. The right response depends on how far the task has progressed.

State of the workHandler responsibility
No business effect has completedStop promptly. Return the delivery for retry, or let the handler consumer apply its cancellation rule.
The business effect completed successfullyExplicitly acknowledge it while the connection is still draining. Handle acknowledgement failure.
An external call may have completed but its result is unknownReconcile or rely on an idempotency key when the work is retried. Cancellation alone cannot tell you whether it succeeded.

A handler that returns after cancellation without explicitly settling is negatively acknowledged, even if it returns normally. The delivery attempt counts; the normal retry limit and dead-letter behavior apply. A successful explicit acknowledgement takes precedence.

The cancellation signal is ctx/message.StoppedCtx in Go, message.signal in TypeScript, and message.stopped() in Rust. Pass it into application operations that support cancellation.

Explicitly acknowledge only after the business effect has completed. Go needs a separate, bounded context because the processing context may already be cancelled. Rust and TypeScript acknowledgement calls do not take the delivery's cancellation signal.

settleCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := message.Ack(settleCtx); err != nil {
log.Printf("acknowledgement failed for message %d: %v", message.ID, err)
}

Keep these calls within the connection's shutdown budget. Only acknowledge after the effect you are acknowledging has actually completed. A timeout or failure leaves an uncertain or unsuccessful outcome; do not assume the business operation will never be delivered again.

Avoid waiting on yourself​

Closing a connection waits for active deliveries. If a handler calls close and waits for it before returning or acknowledging, close can end up waiting for that same handler. The same problem occurs when a consume loop holds an unsettled message and waits for its consumer to stop.

Use this order:

  1. The application's lifecycle code stops admitting new requests that submit queue work.
  2. That lifecycle code starts and awaits connection shutdown.
  3. Handlers respond independently: they finish and acknowledge, or stop and allow retry.
  4. After queue shutdown, the application closes its own pool and flushes its metrics provider.

Keep shutdown out of the handler being drained. A finite connection timeout provides a limit if work gets stuck; it is not a substitute for the correct call sequence.

Be especially careful with a separate consumer stop call. In Go and Rust it has no standalone timeout, and a handler-consumer stop can continue waiting for handler completion. Configuring a connection timeout does not turn every stop call into a timed operation. For application shutdown, close the connection from lifecycle code instead of awaiting each consumer stop first. In TypeScript, consumer stop uses the configured shutdown budget, but the same self-wait problem should still be avoided.

Understand what the deadline leaves behind​

When the deadline passes, unresolved active work is abandoned without refunding its attempt. It becomes eligible for redelivery after its visibility timeout if attempts remain. An abandoned final attempt needs scheduled maintenance to move it to the dead-letter queue.

The database may also have claimed a message whose response was lost during shutdown. That message cannot always be returned immediately; its visibility timeout provides recovery.

An application callback that ignores cancellation may continue running after queue close returns. Shutdown cannot undo its external effects. Use idempotent effects and do not treat a returned close call as proof that every job completed successfully.

For handlers that update PostgreSQL data, Transactional outbox explains how to commit business changes and acknowledgement together.