> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stackshift.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# Pull consumers

> A worker anywhere pulls a batch over HTTP, leases the messages for a visibility timeout, then acks or retries each one by lease id.

> [!TIP]
>
> **Live.** This area is documented as current, user-reliable behavior.

## Goal

Run your own worker process that takes messages off a queue.

## Prerequisites

* A queue with a Pull consumer
* A pull token for the queue, or an API key

## Workflow

**Step 1**

Set the queue's consumer to Pull.

**Step 2**

On the queue page, open Tokens and create a pull token. It is shown once; store it as a secret.

**Step 3**

Run a loop that pulls a batch, works on each message, and acks or retries it.

**Step 4**

Ack before the visibility timeout ends, or the message becomes visible again for another worker.

## Pull tokens

* A pull token starts with sqt\_ and can only pull and ack messages on its own queue. Use it as the API key in any SDK or as a Bearer token.
* Create, list and delete tokens on the queue page or with GET, POST /queues/\{queue}/tokens and DELETE /queues/\{queue}/tokens/\{id}. POST returns the token once.

## Pull and ack over HTTP

* batch\_size is up to 100. visibility\_timeout\_ms is up to 43,200,000 (12 hours).
* Each pulled message carries a lease\_id. Ack or retry by lease id, not message id.
* An ack that arrives after the visibility timeout is still accepted.
* Pull returns at once, with an empty list when nothing is ready. Wait a moment before pulling again.
* stackshift queues tail QUEUE prints messages as they arrive and only reads: it never leases a message or changes its attempts. With --ack it consumes instead, pulling and acking what it prints.

```bash Pull, then ack theme={null}
curl -X POST https://api.stackshift.cloud/api/v1/queues/orders/messages/pull \
  -H "Authorization: Bearer $STACKSHIFT_QUEUE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"batch_size": 10, "visibility_timeout_ms": 30000}'
# {"messages": [{"lease_id": "...", "id": "msg_...", "body": {...}, "content_type": "json", "attempts": 1, "sent_at": "..."}], "backlog_count": 42}

curl -X POST https://api.stackshift.cloud/api/v1/queues/orders/messages/ack \
  -H "Authorization: Bearer $STACKSHIFT_QUEUE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"acks": [{"lease_id": "LEASE_1"}], "retries": [{"lease_id": "LEASE_2", "delay_seconds": 60}]}'
# {"acked": 1, "retried": 1}
```

## Worker loop

```ts JavaScript theme={null}
import { StackShift } from '@stackshift-cloud/sdk'

const client = new StackShift({ apiKey: process.env.STACKSHIFT_QUEUE_TOKEN! })

while (true) {
  const { messages } = await client.queues.pull('orders', { batchSize: 10, visibilityTimeoutMs: 60_000 })
  if (messages.length === 0) {
    await new Promise((resolve) => setTimeout(resolve, 1000))
    continue
  }
  for (const message of messages) {
    try {
      await fulfil(message.body)
      await message.ack()
    } catch {
      await message.retry({ delaySeconds: 60 })
    }
  }
}
```

```python Python theme={null}
import os
import time
from stackshift import StackShift

client = StackShift(api_key=os.environ["STACKSHIFT_QUEUE_TOKEN"])

while True:
    result = client.queues.pull("orders", batch_size=10, visibility_timeout_ms=60_000)
    if not result["messages"]:
        time.sleep(1)
        continue
    for message in result["messages"]:
        try:
            fulfil(message.body)
            message.ack()
        except Exception:
            message.retry(delay_seconds=60)
```

```go Go theme={null}
client, err := stackshift.New(stackshift.Options{APIKey: os.Getenv("STACKSHIFT_QUEUE_TOKEN")})
if err != nil {
	log.Fatal(err)
}
for {
	batch, err := client.Queues.Pull(ctx, "orders", stackshift.QueuePullOptions{BatchSize: 10, VisibilityTimeoutMs: 60000})
	if err != nil || len(batch.Messages) == 0 {
		time.Sleep(time.Second)
		continue
	}
	for _, message := range batch.Messages {
		var order Order
		if err := message.Decode(&order); err != nil || fulfil(order) != nil {
			_ = message.RetryAfter(ctx, 60)
			continue
		}
		_ = message.Ack(ctx)
	}
}
```

```php PHP theme={null}
$queues = new \StackShift\QueuesClient(getenv('STACKSHIFT_QUEUE_TOKEN'));

while (true) {
    $pulled = $queues->pull('orders', ['batch_size' => 10, 'visibility_timeout_ms' => 60000]);
    if ($pulled['messages'] === []) {
        sleep(1);
        continue;
    }
    foreach ($pulled['messages'] as $message) {
        try {
            fulfil($message->body);
            $message->ack();
        } catch (\Throwable $e) {
            $message->retry(60);
        }
    }
}
```

```ruby Ruby theme={null}
require "stackshift/queues"

queues = StackShift::QueuesClient.new(api_key: ENV.fetch("STACKSHIFT_QUEUE_TOKEN"))

loop do
  batch = queues.pull("orders", batch_size: 10, visibility_timeout_ms: 60_000)
  if batch["messages"].empty?
    sleep 1
    next
  end
  batch["messages"].each do |message|
    fulfil(message.body)
    message.ack
  rescue StandardError
    message.retry(delay_seconds: 60)
  end
end
```

```bash CLI theme={null}
stackshift queues pull orders --batch-size 10 --visibility-timeout 60s
stackshift queues ack orders LEASE_ID_1 LEASE_ID_2
stackshift queues retry orders LEASE_ID_3 --delay 60s
```

## Workers in a StackShift project

Run the loop as a worker service in the same project and give it the pull token as an environment variable. It scales like any other worker; more replicas pull more batches in parallel.

## Expected result

> [!TIP]
>
> Your worker drains the queue; the queue page shows the out rate and the last time each token was used.

## Common failures

> [!WARNING]
>
> * 409 queue\_delivery\_paused: delivery is paused. Wait and pull again, or resume the queue.
> * Messages are handled twice: the work took longer than the visibility timeout. Raise visibility\_timeout\_ms (up to 12 hours) or use smaller batches.
> * A pull token is refused on another queue: pull tokens only work on the queue they were made for.

## Related guides

> [card] [Batching, retries and delays](https://docs.stackshift.cloud/queues/batching-retries-and-delays.md)
>
> How batch size and wait, retries, retry delays, concurrency and delivery guarantees work.

> [card] [Laravel queue driver](https://docs.stackshift.cloud/queues/laravel.md)
>
> Use StackShift Queues as a Laravel queue connection. dispatch() and php artisan queue:work keep working as they are.

> [card] [Limits and error codes](https://docs.stackshift.cloud/queues/limits-and-errors.md)
>
> Sizes, rates, retention and the error codes the Queues API returns when a limit is reached.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.