# Delay Policy (/sdks/nodejs/how-to/queues/delay-policy)



<Callout type="info" title="Which to use">
  For the task-oriented how-to, see [Delayed Messages](./delayed-messages). This page focuses on the `policy: { delaySeconds }` delay-policy option itself — its evaluation point and interaction with redelivery.
</Callout>

## Overview [#overview]

`policy: { delaySeconds }` is the option passed to `createQueueMessage` that defers when a queued message becomes visible to consumers — set it before sending, and the broker excludes the message from delivery until the countdown expires. It starts the moment the broker accepts the message, not when the client sends it, and is evaluated once, at send time.

**Gotchas:** the delay is a floor, not a guarantee — the message becomes *eligible* when the timer expires, but actual delivery still waits for a consumer to poll, so don't rely on it for precise scheduling. It's one-shot: there's no recurrence or cron-like behavior, so long or repeating delays need application logic on top. And it's independent of redelivery — a delayed message that's later nacked or times out after delivery follows normal visibility-timeout/retry rules, not the original send-time delay.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Node.js SDK installed (`npm install kubemq-js`)

## Code [#code]

```typescript title="delay-policy.ts"
/**
 * Example: Queue Stream — Delayed Message Delivery
 *
 * Demonstrates sending messages with a delay policy via the stream
 * upstream API. Messages are not delivered to consumers until the
 * specified delay has elapsed.
 *
 * Prerequisites:
 *   - KubeMQ server running on localhost:50000
 *
 * Run: npx tsx examples/queues-stream/delay-policy.ts
 */
import { KubeMQClient, createQueueMessage } from 'kubemq-js';

async function main(): Promise<void> {
  const client = await KubeMQClient.create({
    address: 'localhost:50000',
    clientId: 'js-queues-stream-delay-policy-client',
  });

  try {
    const upstream = client.createQueueUpstream();

    const result = await upstream.send([
      createQueueMessage({
        channel: 'js-queues-stream.delay-policy',
        body: 'Order #1 — deliver after 5 seconds',
        policy: { delaySeconds: 5 },
      }),
      createQueueMessage({
        channel: 'js-queues-stream.delay-policy',
        body: 'Order #2 — deliver after 10 seconds',
        policy: { delaySeconds: 10 },
      }),
    ]);

    console.log('Sent', result.results.length, 'delayed messages');
    for (const r of result.results) {
      const delayed =
        r.delayedTo instanceof Date && !isNaN(r.delayedTo.getTime())
          ? r.delayedTo.toISOString()
          : 'N/A';
      console.log(`  ${r.messageId}: delayedTo=${delayed}`);
    }

    console.log('Waiting 6 seconds for first message to become available...');
    await new Promise((resolve) => setTimeout(resolve, 6000));

    const handle = client.streamQueueMessages({
      channel: 'js-queues-stream.delay-policy',
      maxMessages: 10,
      waitTimeoutSeconds: 3,
    });

    handle.onMessages((msgs) => {
      console.log(`Received ${msgs.length} message(s):`);
      for (const msg of msgs) {
        console.log(`  ${new TextDecoder().decode(msg.body)}`);
        msg.ack();
      }
    });

    handle.onError((err) => {
      console.error('Downstream error:', err.message);
    });

    await new Promise((resolve) => setTimeout(resolve, 5000));
    handle.close();
    upstream.close();
  } finally {
    await client.close();
  }
}

main().catch(console.error);

```

## How It Works [#how-it-works]

* `policy: { delaySeconds: 5 }` and `{ delaySeconds: 10 }` tell the server to hold each message for the specified duration before making it visible to consumers.
* The `QueueUpstreamResult` from `upstream.send()` includes `delayedTo` — a `Date` showing when the message will become available — confirming the server accepted the policy.
* After waiting 6 seconds, only the first message (5 s delay) is visible; the second (10 s delay) is still hidden and requires waiting the remaining 4 seconds.
* `msg.ack()` inside `onMessages` is called synchronously on the stream message; for stream API messages, ack does not return a Promise.

## Related [#related]

* [Delayed Messages](./delayed-messages) — task-oriented walkthrough for sending delayed messages
* [Pattern overview](/learn/queues/getting-started)
* [Node.js SDK Reference](/sdks/nodejs/reference)
* [Send & Receive](/sdks/nodejs/tutorials/send-receive)
* [Ack All](/sdks/nodejs/how-to/queues/ack-all)
