### Initialize Next.js and Install QStash Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Commands to create a new Next.js project, navigate to the directory, install the QStash SDK, and start the development server. ```bash npx create-next-app@latest qstash-bg-job ``` ```bash cd qstash-bg-job ``` ```bash npm install @upstash/qstash ``` ```bash npm run dev ``` -------------------------------- ### Install QStash SDK Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Install the package using pip. ```bash pip install qstash ``` -------------------------------- ### Install QStash Library Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Install the required Upstash QStash SDK. ```bash npm install @upstash/qstash ``` -------------------------------- ### Install Required Packages Source: https://upstash.com/docs/qstash/recipes/periodic-data-updates Install the necessary Upstash QStash and Redis client libraries for the project. ```bash npm install @upstash/qstash @upstash/redis ``` -------------------------------- ### Start QStash Dev Server with NPM Source: https://upstash.com/docs/qstash/howto/local-development Use the QStash CLI via npx to start the development server, optionally specifying custom ports. ```javascript npx @upstash/qstash-cli dev // Start on a different port npx @upstash/qstash-cli dev -port=8081 // Start with a custom log server port npx @upstash/qstash-cli dev -port=8081 -log-port=9000 ``` -------------------------------- ### Install Vercel CLI Source: https://upstash.com/docs/qstash/overall/llms-txt Globally install the Vercel CLI for deployment. ```bash npm install -g vercel ``` -------------------------------- ### Run Development Server Source: https://upstash.com/docs/qstash/overall/llms-txt Start the local development server. ```bash npm run dev ``` -------------------------------- ### Initialize Synchronous Client Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Basic setup for the synchronous QStash client. ```python from qstash import QStash client = QStash("") client.message.publish_json(...) ``` -------------------------------- ### Initialize Asynchronous Client Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Basic setup for the asynchronous QStash client using asyncio. ```python import asyncio from qstash import AsyncQStash async def main(): client = AsyncQStash("") await client.message.publish_json(...) asyncio.run(main()) ``` -------------------------------- ### QStash Dev Server Startup Output Source: https://upstash.com/docs/qstash/howto/local-development Example output displayed by the SDK when the dev server initializes. ```text [QStash Dev] Server running at http://127.0.0.1:8080 Console: https://console.upstash.com/qstash/local-mode-user?port=8080 ``` -------------------------------- ### QStash Error Response Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example of an error response indicating invalid input parameters. ```json { "error": "Invalid input parameters." } ``` -------------------------------- ### Initialize Python Project Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Commands to create the project directory and install the required Redis dependency. ```bash mkdir clean-db-cron ``` ```bash cd clean-db-cron ``` ```bash pip install upstash-redis ``` -------------------------------- ### Retrieve Message Details API Response Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure for a successful GET request to the message details endpoint. ```json { "messageId": "msg_abc123", "url": "https://example.com/webhook", "topicName": "my-topic", "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"key\": \"value\"}", "maxRetries": 3, "createdAt": 1678886400000, "callback": "https://example.com/callback", "queueName": "my-queue" } ``` ```json { "error": { "message": "Message not found" } } ``` -------------------------------- ### Deploy to Vercel Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Commands to install the Vercel CLI and deploy the application. ```bash npm install -g vercel ``` ```bash vercel ``` -------------------------------- ### Install Upstash Redis Package Source: https://upstash.com/docs/qstash/overall/llms-txt Install the necessary Python package for interacting with Upstash Redis. ```bash pip install upstash-redis ``` -------------------------------- ### Retrieve Logs API Examples Source: https://upstash.com/docs/qstash/overall/llms-txt Examples for retrieving logs for published messages using cURL, TypeScript, and Python. ```shell curl https://qstash.upstash.io/v2/logs \ -H "Authorization: Bearer XXX" ``` ```typescript const client = new Client({ token: "" }); const logs = await client.logs() ``` ```python from qstash import QStash client = QStash("") client.event.list() ``` -------------------------------- ### Retrieve Signing Keys JSON Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure for the GET /v2/keys endpoint. ```json { "current": "your_current_signing_key", "next": "your_next_signing_key" } ``` -------------------------------- ### Queue Response Examples Source: https://upstash.com/docs/qstash/overall/llms-txt JSON response structures for listing queues in a QStash account. ```json [ { "name": "my-queue", "createdAt": 1678886400000, "updatedAt": 1678886400000, "parallelism": 10, "paused": false, "lag": 0 } ] ``` ```json [ { "name": "my-queue", "createdAt": 1678886400000, "updatedAt": 1678886400000, "parallelism": 10, "paused": false, "lag": 5 } ] ``` -------------------------------- ### Enqueue Message Success Response Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response returned upon successfully enqueuing a message. ```json { "messageId": "msg_abc123", "delay": 0 } ``` -------------------------------- ### JWT Header Example Source: https://upstash.com/docs/qstash/features/security Example of the header section of the JWT sent in the Upstash-Signature header. ```json { "alg": "HS256", "typ": "JWT" } ``` -------------------------------- ### Unpin Flow Control Request Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example of a POST request to unpin flow control configuration. ```json { "example": "POST /v2/flowControl/my-key/unpin?parallelism=true&rate=true" } ``` -------------------------------- ### Error Response (404) Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON structure for a 404 Not Found error response. ```json { "error": "Message not found" } ``` -------------------------------- ### Enqueue Message Request Example Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON payload for sending a message to a destination URL. ```json { "body": "Hello, QStash!", "to": "https://example.com/webhook" } ``` -------------------------------- ### Get DLQ message response examples Source: https://upstash.com/docs/qstash/overall/llms-txt JSON representations of successful and error responses when fetching a message from the Dead Letter Queue. ```json { "messageId": "msg_abc123", "url": "https://example.com/webhook", "topicName": "my-topic", "endpointName": "my-endpoint", "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"key\": \"value\"}", "bodyBase64": "", "maxRetries": 3, "notBefore": 1678886400000, "createdAt": 1678886300000, "callback": "https://example.com/callback", "failureCallback": "https://example.com/failure-callback", "queueName": "my-queue", "scheduleId": "sch_xyz789", "callerIP": "192.168.1.1", "labels": ["important"] } ``` ```json { "message": "Message not found in DLQ" } ``` -------------------------------- ### Flow Control Status Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response for the GET /v1/flowcontrol/status endpoint. ```json { "flowControlKey": "my-flow-key", "waitListSize": 10, "parallelismMax": 5, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ``` -------------------------------- ### Start QStash development server with custom ports Source: https://upstash.com/docs/qstash/howto/local-development Configures specific ports for the main API server and the log server. ```bash # Start with custom ports for both components $ ./qstash dev -port=8080 -log-port=9000 ``` -------------------------------- ### View Deno Deploy Logs Source: https://upstash.com/docs/qstash/quickstarts/deno-deploy Example output observed in the Deno Deploy logs after a successful webhook verification. ```bash europe-west3isolate start time: 2.21 ms Listening on http://localhost:8000/ The signature was valid ``` -------------------------------- ### Run QStash CLI Development Server Source: https://upstash.com/docs/qstash/overall/llms-txt Starts the local QStash development server using NPX, with optional port configuration. ```bash npx @upstash/qstash-cli dev ``` ```bash // Start on a different port npx @upstash/qstash-cli dev -port=8081 ``` -------------------------------- ### Initialize AWS Lambda Project Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Commands to create a new directory, initialize a CDK TypeScript app, and install required dependencies. ```bash mkdir my-app cd my-app cdk init app -l typescript npm i esbuild @upstash/qstash mkdir lambda touch lambda/index.ts ``` -------------------------------- ### Get Message by ID Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure when retrieving a message by its unique ID. ```json { "message": { "id": "msg_abc123", "content": "Hello, QStash!", "contentType": "text/plain", "createdAt": "2023-10-27T10:00:00Z" } } ``` -------------------------------- ### JWT Payload Example Source: https://upstash.com/docs/qstash/features/security Example of the payload section of the JWT sent in the Upstash-Signature header. ```json { "iss": "Upstash", "sub": "https://qstash-remote.requestcatcher.com/test", "exp": 1656580612, "nbf": 1656580312, "iat": 1656580312, "jti": "jwt_67kxXD6UBAk7DqU6hzuHMDdXFXfP", "body": "qK78N0k3pNKI8zN62Fq2Gm-_LtWkJk1z9ykio3zZvY4=" } ``` -------------------------------- ### Publish Message with Custom Headers Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON body for publishing a message. ```json { "body": "This is the message body." } ``` -------------------------------- ### GET /v2/keys Source: https://upstash.com/docs/qstash/api-reference/signing-keys/get-signing-keys Retrieve your current and next signing keys. ```APIDOC ## GET /v2/keys ### Description Retrieve your current and next signing keys. ### Method GET ### Endpoint /v2/keys ### Response #### Success Response (200) - **current** (string) - The current signing key. - **next** (string) - The next signing key. #### Response Example { "current": "sig_12345", "next": "sig_67890" } ``` -------------------------------- ### List Schedules via HTTP GET Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve all schedules by sending a GET request to the /v2/schedules endpoint. ```http GET /v2/schedules ``` -------------------------------- ### Retrieve Schedules Source: https://upstash.com/docs/qstash/overall/llms-txt Example of a successful response when querying for existing schedules. ```APIDOC ## GET /schedules ### Description Retrieves a list of schedules with their configuration and status details. ### Response #### Success Response (200) - **scheduleId** (string) - The unique identifier of the schedule. - **cron** (string) - The cron expression. - **destination** (string) - The target URL. - **createdAt** (number) - Timestamp of creation. - **method** (string) - HTTP method used for the request. - **header** (object) - Headers sent with the request. - **body** (string) - The request body. - **retries** (number) - Number of retries configured. - **delay** (number) - Delay in seconds. - **callback** (string) - Success callback URL. - **failureCallback** (string) - Failure callback URL. - **callerIp** (string) - IP address of the caller. - **isPaused** (boolean) - Whether the schedule is paused. - **flowControlKey** (string) - Flow control key. - **parallelism** (number) - Parallelism limit. - **rate** (number) - Rate limit. - **period** (number) - Period for rate limiting. - **retryDelayExpression** (string) - Expression for retry delay. - **label** (string) - Schedule label. - **lastScheduleTime** (number) - Timestamp of the last execution. - **nextScheduleTime** (number) - Timestamp of the next execution. - **lastScheduleStates** (object) - Status of the last execution. ### Response Example [ { "scheduleId": "sch_abc123", "cron": "* * * * *", "destination": "https://example.com/webhook", "createdAt": 1678886400000, "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"message\": \"Hello, world!\"}", "retries": 3, "delay": 60, "callback": "https://example.com/callback", "failureCallback": "https://example.com/failure", "callerIp": "192.168.1.1", "isPaused": false, "flowControlKey": "fc_key_123", "parallelism": 10, "rate": 100, "period": 60, "retryDelayExpression": "1m * pow(2, attempt)", "label": "my-schedule", "lastScheduleTime": 1678886400000, "nextScheduleTime": 1678886460000, "lastScheduleStates": { "status": "success" } } ] ``` -------------------------------- ### Initialize Go Project Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Commands to create a new directory and initialize a Go module. ```bash mkdir flyio-go cd flyio-go go mod init flyio-go ``` -------------------------------- ### OpenAPI Specification for Get a Schedule Source: https://upstash.com/docs/qstash/api-reference/schedules/get-a-schedule Defines the GET endpoint for retrieving schedule details by scheduleId. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/schedules/{scheduleId}: get: tags: - Schedules summary: Get a Schedule description: Get details of a specific schedule parameters: - name: scheduleId in: path required: true schema: type: string description: The ID of the schedule to retrieve. responses: '200': description: '' content: application/json: schema: $ref: '#/components/schemas/Schedule' '404': description: Schedule not found content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: Schedule: type: object required: - scheduleId - cron - destination - createdAt - method - isPaused properties: scheduleId: type: string description: Unique identifier for the schedule cron: type: string description: The cron expression used to schedule the message destination: type: string description: The destination URL or URL Group name createdAt: type: integer format: int64 description: The creation timestamp of the schedule in unix milliseconds method: type: string description: The HTTP method used for the scheduled message header: type: object additionalProperties: type: array items: type: string description: Map of header names to arrays of header values body: type: string description: The body of the scheduled message retries: type: integer description: The number of retries for the scheduled message delay: type: integer description: The delay in seconds before the scheduled message is sent callback: type: string description: The callback URL for the scheduled message failureCallback: type: string description: The failure callback URL for the scheduled message callerIp: type: string description: The IP address of the client that created the schedule isPaused: type: boolean description: Whether the schedule is paused flowControlKey: type: string description: The flow control key used for rate limiting parallelism: type: integer description: The parallelism value used for flow control rate: type: integer description: The rate value used for flow control period: type: integer description: The period value used for flow control retryDelayExpression: type: string description: The retry delay expression used for calculating retry delays label: type: string deprecated: true description: >- The label assigned to the scheduled message. Deprecated in favor of `labels`. labels: type: array items: type: string description: The list of labels assigned to the scheduled message. lastScheduleTime: type: integer format: int64 description: The last time the schedule was triggered in unix milliseconds nextScheduleTime: type: integer format: int64 description: The next scheduled trigger time in unix milliseconds ``` -------------------------------- ### GET /flowControl/global/parallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the global parallelism settings for the QStash service. ```APIDOC ## GET /flowControl/global/parallelism ### Description Retrieves the global parallelism settings for the QStash service. ### Method GET ``` -------------------------------- ### Bundle Lambda Function with Makefile Source: https://upstash.com/docs/qstash/overall/llms-txt Automates dependency installation and packaging of a Python Lambda function into a zip archive. ```makefile zip: rm -rf dist pip3 install --target ./dist pyjwt cp lambda_function.py ./dist/lambda_function.py cd dist && zip -r lambda.zip . mv ./dist/lambda.zip ./ ``` -------------------------------- ### Get Schedule Details API Documentation Source: https://upstash.com/docs/qstash/overall/llms-txt Describes the GET /schedules/{scheduleId} endpoint for fetching specific schedule information. ```text ## GET /schedules/{scheduleId} ### Description Fetches the details of a specific schedule identified by its ID. ### Method GET ### Endpoint /schedules/{scheduleId} ### Parameters #### Path Parameters - **scheduleId** (string) - Required - The unique identifier of the schedule to retrieve. ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the schedule. - **cron** (string) - The cron syntax of the schedule. - **destination** (string) - The destination URL or URL group. - **isPaused** (boolean) - Indicates if the schedule is currently paused. ``` -------------------------------- ### Get Signing Keys OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/signing-keys/get-signing-keys Defines the GET /v2/keys endpoint for retrieving signing keys within the QStash REST API. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/keys: get: tags: - Signing Keys summary: Get Signing Keys description: Retrieve your current and next signing keys responses: '200': description: Signing keys retrieved successfully content: application/json: schema: $ref: '#/components/schemas/SigningKeys' components: schemas: SigningKeys: type: object properties: current: type: string description: The current signing key. next: type: string description: The next signing key. securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### GET /v2/schedules Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves a list of all schedules configured in the QStash account. ```APIDOC ## GET /v2/schedules ### Description Retrieves a list of all schedules configured in the QStash account. ### Method GET ### Endpoint /v2/schedules ``` -------------------------------- ### GET /v2/queues Source: https://upstash.com/docs/qstash/api-reference/queues/list-queues Retrieves a list of all queues configured in the QStash account. ```APIDOC ## GET /v2/queues ### Description List all your queues. ### Method GET ### Endpoint /v2/queues ### Response #### Success Response (200) - **Array of Queues** (array) - List of queues - **name** (string) - The name of the queue. - **createdAt** (integer) - The creation timestamp of the queue in Unix milliseconds - **updatedAt** (integer) - The last update timestamp of the queue in Unix milliseconds - **parallelism** (integer) - The number of parallel consumers consuming from the queue - **paused** (boolean) - Whether the queue is paused - **lag** (integer) - The number of unprocessed messages that exist in the queue ``` -------------------------------- ### Bundle Lambda function with Makefile Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Use this Makefile script to install dependencies and package the Lambda function into a zip file for deployment. ```yaml zip: rm -rf dist pip3 install --target ./dist pyjwt cp lambda_function.py ./dist/lambda_function.py cd dist && zip -r lambda.zip . mv ./dist/lambda.zip ./ ``` -------------------------------- ### Full Worker Implementation Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers The complete example showing the integration of the Receiver and signature verification within a fetch handler. ```ts import { Receiver } from "@upstash/qstash"; export interface Env { QSTASH_CURRENT_SIGNING_KEY: string; QSTASH_NEXT_SIGNING_KEY: string; } export default { async fetch(request, env, ctx): Promise { const receiver = new Receiver({ currentSigningKey: env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: env.QSTASH_NEXT_SIGNING_KEY, }); const body = await request.text(); const isValid = await receiver.verify({ signature: request.headers.get("Upstash-Signature")!, body, }); if (!isValid) { return new Response("Invalid signature", { status: 401 }); } // signature is valid return new Response("Hello World!"); }, } satisfies ExportedHandler; ``` -------------------------------- ### Initialize Project Directory Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Commands to create the project folder and the main Python file. ```bash mkdir aws-lambda cd aws-lambda touch lambda_function.py ``` -------------------------------- ### QStash Batch Response Example Source: https://upstash.com/docs/qstash/overall/llms-txt Illustrates the JSON structure of a batch API response for messages, including IDs and deduplication status. ```json [ { "messageId": "msg_abc123", "deduplicated": false }, { "messageId": "msg_def456", "deduplicated": true } ] ``` -------------------------------- ### Get Global Parallelism with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches global parallelism settings using the QStash Python client. ```python from qstash import QStash client = QStash("") info = client.flow_control.get_global_parallelism() print(info) ``` -------------------------------- ### Get a Queue OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/queues/get-a-queue Defines the GET endpoint for retrieving queue details, including path parameters and response schemas. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/queues/{queueName}: get: tags: - Queues summary: Get a Queue description: Get details of a specific queue parameters: - name: queueName in: path required: true schema: type: string description: The name of the queue to retrieve. responses: '200': description: '' content: application/json: schema: $ref: '#/components/schemas/Queue' '400': description: >- Queue name is invalid. Queue names can only contain alphanumeric characters, hyphens, periods, and underscores. content: application/json: schema: $ref: '#/components/schemas/Error' '404': description: Queue not found content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: Queue: type: object properties: name: type: string description: The name of the queue. createdAt: type: integer format: int64 description: The creation timestamp of the queue in Unix milliseconds updatedAt: type: integer format: int64 description: The last update timestamp of the queue in Unix milliseconds parallelism: type: integer description: The number of parallel consumers consuming from the queue paused: type: boolean description: Whether the queue is paused lag: type: integer description: The number of unprocessed messages that exist in the queue Error: type: object required: - error properties: error: type: string description: Error message securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Get message logs Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve logs for published messages. ```shell curl https://qstash.upstash.io/v2/logs \ -H "Authorization: Bearer XXX" ``` ```typescript const client = new Client({ token: "" }); const logs = await client.logs() ``` ```python from qstash import QStash client = QStash("") client.event.list() # Async version is also available ``` -------------------------------- ### GET /v2/logs Source: https://upstash.com/docs/qstash/api-reference/logs/list-logs Paginate through logs of published messages. ```APIDOC ## GET /v2/logs ### Description Paginate through logs of published messages. ### Method GET ### Endpoint /v2/logs ### Parameters #### Query Parameters - **cursor** (string) - Optional - By providing a cursor you can paginate through all of the logs - **messageId** (string) - Optional - Filter logs by message ID - **state** (string) - Optional - Filter logs by message state (CREATED, ACTIVE, RETRY, ERROR, IN_PROGRESS, DELIVERED, CANCEL_REQUESTED, CANCELLED) - **url** (string) - Optional - Filter logs by destination URL - **topicName** (string) - Optional - Filter logs by URL Group name - **scheduleId** (string) - Optional - Filter logs by schedule ID - **queueName** (string) - Optional - Filter logs by queue name - **fromDate** (integer) - Optional - Filter logs by starting date, in milliseconds (Unix timestamp). This is inclusive. - **toDate** (integer) - Optional - Filter logs by ending date, in milliseconds (Unix timestamp). This is inclusive. - **count** (integer) - Optional - The number of log entries to return (default: 100, max: 100) - **label** (array) - Optional - Filter logs by label. Supports multi-value filtering. ### Response #### Success Response (200) - **cursor** (string) - A cursor which you can use in subsequent requests to paginate through all logs. ``` -------------------------------- ### GET /v2/dlq Source: https://upstash.com/docs/qstash/api-reference/dlq/list-dlq-messages List and paginate through all messages currently in the DLQ. ```APIDOC ## GET /v2/dlq ### Description List and paginate through all messages currently in the DLQ. ### Method GET ### Endpoint /v2/dlq ### Parameters #### Query Parameters - **cursor** (string) - Optional - By providing a cursor you can paginate through all of the messages in the DLQ - **messageId** (string) - Optional - Filter DLQ messages by message ID - **url** (array) - Optional - Filter DLQ messages by destination URL. Supports multiple values. - **topicName** (array) - Optional - Filter DLQ messages by URL Group name. Supports multiple values. - **scheduleId** (array) - Optional - Filter DLQ messages by schedule ID. Supports multiple values. - **queueName** (array) - Optional - Filter DLQ messages by queue name. Supports multiple values. - **fromDate** (integer) - Optional - Filter DLQ messages by starting date, in milliseconds (Unix timestamp). This is inclusive. - **toDate** (integer) - Optional - Filter DLQ messages by ending date, in milliseconds (Unix timestamp). This is inclusive. - **responseStatus** (array) - Optional - Filter DLQ messages by HTTP response status code of the last delivery attempt. Supports multiple values. - **callerIp** (array) - Optional - Filter DLQ messages by IP address of the publisher. Supports multiple values. - **label** (array) - Optional - Filter DLQ messages by label. Supports multiple values. - **count** (integer) - Optional - The number of messages to return (default: 100, max: 100). ### Response #### Success Response (200) - **cursor** (string) - A cursor which you can use in subsequent requests to paginate through all messages. ``` -------------------------------- ### GET /v2/globalParallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves global parallelism data for QStash. ```APIDOC ## GET /v2/globalParallelism ### Description Retrieves global parallelism data for QStash. ### Method GET ### Endpoint /v2/globalParallelism ### Request Example ```bash curl -X GET https://qstash.upstash.io/v2/globalParallelism \ -H "Authorization: Bearer " ``` ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes a new directory for a project. ```bash mkdir clean-db-cron ``` -------------------------------- ### Get all logs with pagination Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches all logs with pagination using a cursor. ```APIDOC ## Get all logs with pagination using cursor ### Description Fetches all logs with pagination. The cursor allows you to iterate through results when there are a large number of logs. ### Method `client.logs({ cursor })` ### Parameters #### Query Parameters - **cursor** (string | null) - Optional - The cursor for pagination. If null, fetches the first page. ``` -------------------------------- ### GET /v2/logs Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieves logs for all published messages. ```APIDOC ## GET /v2/logs ### Description Retrieves logs for all messages that have been published. ### Method GET ### Endpoint https://qstash.upstash.io/v2/logs ``` -------------------------------- ### GET /schedules Source: https://upstash.com/docs/qstash/api-reference/schedules/list-schedules Retrieves a list of all schedules currently defined in the system. ```APIDOC ## GET /schedules ### Description List all schedules configured in the QStash service. ### Method GET ### Endpoint /schedules ``` -------------------------------- ### Initialize Fly.io App Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Use the flyctl launch command to scan the source code and generate the fly.toml configuration file. ```bash $ flyctl launch Creating app in /Users/andreasthomas/github/upstash/qstash-examples/fly.io/go Scanning source code Detected a Go app Using the following build configuration: Builder: paketobuildpacks/builder:base Buildpacks: gcr.io/paketo-buildpacks/go ? App Name (leave blank to use an auto-generated name): Automatically selected personal organization: Andreas Thomas ? Select region: fra (Frankfurt, Germany) Created app winer-cherry-9545 in organization personal Wrote config file fly.toml ? Would you like to setup a Postgresql database now? No ? Would you like to deploy now? No Your app is ready. Deploy with `flyctl deploy` ``` -------------------------------- ### GET /v2/schedules Source: https://upstash.com/docs/qstash/api-reference/schedules/list-schedules Retrieves a list of all schedules currently configured in the system. ```APIDOC ## GET /v2/schedules ### Description List all schedules configured in the QStash account. ### Method GET ### Endpoint /v2/schedules ### Response #### Success Response (200) - **schedules** (array) - A list of Schedule objects. #### Schedule Object - **scheduleId** (string) - Unique identifier for the schedule - **cron** (string) - The cron expression used to schedule the message - **destination** (string) - The destination URL or URL Group name - **createdAt** (integer) - The creation timestamp of the schedule in unix milliseconds - **method** (string) - The HTTP method used for the scheduled message - **isPaused** (boolean) - Whether the schedule is paused ``` -------------------------------- ### Initialize QStash Client Source: https://upstash.com/docs/qstash/sdks/ts/gettingstarted Basic client initialization using your QStash token. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "", }); ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the global parallelism settings for the QStash account. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.getGlobalParallelism(); console.log(info.parallelismMax); console.log(info.parallelismCount); ``` -------------------------------- ### Batching messages with headers and body Source: https://upstash.com/docs/qstash/features/batch Examples of sending multiple messages in a single batch request. ```shell curl -XPOST https://qstash.upstash.io/v2/batch -H "Authorization: Bearer XXX" \ -H "Content-Type: application/json" \ -d ' [ { "destination": "myUrlGroup", "headers":{ "Upstash-Delay":"5s", "Upstash-Forward-Hello":"123456" }, "body": "Hello World" }, { "destination": "https://example.com/destination1", "headers":{ "Upstash-Delay":"7s", "Upstash-Forward-Hello":"789" } }, { "destination": "https://example.com/destination2", "headers":{ "Upstash-Delay":"9s", "Upstash-Forward-Hello":"again" } } ]' ``` ```typescript const client = new Client({ token: "" }); // Each message is the same as the one you would send with the publish endpoint const msgs = [ { urlGroup: "myUrlGroup", delay: 5, body: "Hello World", headers: { hello: "123456", }, }, { url: "https://example.com/destination1", delay: 7, headers: { hello: "789", }, }, { url: "https://example.com/destination2", delay: 9, headers: { hello: "again", }, body: { Some: "Data", }, }, ]; const res = await client.batchJSON(msgs); ``` ```python from qstash import QStash client = QStash("") client.message.batch_json( [ { "url_group": "my-url-group", "delay": "5s", "body": {"hello": "world"}, "headers": {"random": "header"}, }, { "url": "https://example.com/destination1", "delay": "1m", }, { "url": "https://example.com/destination2", "body": {"hello": "again"}, }, ] ) ``` -------------------------------- ### Define Upstash-Delay Header Format Source: https://upstash.com/docs/qstash/overall/llms-txt Examples of valid duration strings for the Upstash-Delay header. ```text 50s ``` ```text 1d10h30m ``` ```text 10h ``` ```text 1d ``` -------------------------------- ### View QStash CLI help Source: https://upstash.com/docs/qstash/howto/local-development Displays available flags and configuration options for the dev command. ```bash $ ./qstash dev --help Usage of dev: -log-port int Port to run the QStash log server on [env QSTASH_DEV_LOG_PORT] -port int Port to run the QStash server on [env QSTASH_DEV_PORT] (default 8080) -quota string The quota of users [env QSTASH_DEV_QUOTA] (default "payg") ``` -------------------------------- ### Example delivered message structure Source: https://upstash.com/docs/qstash/howto/publishing Shows the resulting body and headers delivered to the destination API. ```json // body { "hello": "world" } // headers My-Header: my-value Content-Type: application/json ``` -------------------------------- ### Start ngrok tunnel Source: https://upstash.com/docs/qstash/howto/local-tunnel Initiate a tunnel to forward traffic from a public ngrok URL to your local port. ```bash $ ngrok http 3000 Session Status online Account Andreas Thomas (Plan: Free) Version 3.1.0 Region Europe (eu) Latency - Web Interface http://127.0.0.1:4040 Forwarding https://e02f-2a02-810d-af40-5284-b139-58cc-89df-b740.eu.ngrok.io -> http://localhost:3000 Connections ttl opn rt1 rt5 p50 p90 0 0 0.00 0.00 0.00 0.00 ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/qstash/overall/llms-txt Command to change into the project directory. ```bash cd qstash-bg-job ``` -------------------------------- ### Get Queue Details Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves configuration details for a specific queue using different interfaces. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() ``` ```python from qstash import QStash client = QStash ("") client.queue.get("my-queue") ``` -------------------------------- ### List URL Groups Response Example Source: https://upstash.com/docs/qstash/overall/llms-txt JSON structure of a successful response when listing URL Groups. ```json { "example": "[ { "name": "my-url-group", "createdAt": 1678886400000, "updatedAt": 1678886400000, "endpoints": [ { "name": "my-endpoint", "url": "https://example.com/webhook" } ] } ]" } ``` -------------------------------- ### GET /v2/logs Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve logs for published messages using the QStash API. ```APIDOC ## GET /v2/logs ### Description Retrieve logs for published messages. ### Method GET ### Endpoint `https://qstash.upstash.io/v2/logs` ### Headers - `Authorization`: Bearer ### Response #### Success Response (200) - `logs`: (array) - Array of log objects ``` -------------------------------- ### Get a Message OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/messages/get-a-message Defines the GET endpoint for retrieving message details and the associated schema. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/messages/{messageId}: get: tags: - Messages summary: Get a Message description: Retrieve details of a specific message parameters: - name: messageId in: path required: true schema: type: string description: The identifier of the message to retrieve. responses: '200': description: Message details content: application/json: schema: $ref: '#/components/schemas/Message' '404': description: Message not found content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: Message: type: object properties: messageId: type: string description: Unique identifier for the message url: type: string description: The URL to which the message should be delivered. topicName: type: string description: >- The URL Group (a.k.a. topic) name if this message was sent to a URL Group. endpointName: type: string description: >- The endpoint name of the message if the endpoint is given a name within the URL group. method: type: string description: The HTTP method to use for the message. header: type: object additionalProperties: type: array items: type: string description: The HTTP headers sent to your API. body: type: string description: >- The body of the message if it is composed of utf8 chars only, empty otherwise. bodyBase64: type: string description: >- The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. maxRetries: type: integer description: >- The number of retries that should be attempted in case of delivery failure. notBefore: type: integer format: int64 description: >- The unix timestamp in milliseconds before which the message should not be delivered. createdAt: type: integer format: int64 description: The unix timestamp in milliseconds when the message was created. callback: type: string description: >- The url where we send a callback each time the message is attempted to be delivered. failureCallback: type: string description: The url where we send a callback to after the message is failed queueName: type: string description: The name of the queue if the message is enqueued to a queue. scheduleId: type: string description: >- The scheduleId of the message if the message is triggered by a schedule callerIP: type: string description: IP address of the publisher of this message. label: type: string deprecated: true description: >- The label of the message assigned by the user. Deprecated in favor of `labels`. labels: type: array items: type: string description: The list of labels assigned to the message by the user. flowControlKey: type: string description: The flow control key used for rate limiting. ``` -------------------------------- ### Create Schedule Request Example Source: https://upstash.com/docs/qstash/overall/llms-txt JSON body structure for creating a recurring schedule via the POST /v2/schedules/{url} endpoint. ```json { "destination": "https://my-api...", "cron": "0 * * * *", "callback": "https://my-callback...", "failureCallback": "https://my-failure-callback..." } ``` -------------------------------- ### Create a schedule that runs every 5 minutes Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Initializes a QStash client to create a schedule with a cron expression. ```python from qstash import QStash client = QStash("") schedule_id = client.schedule.create( destination="https://my-api...", cron="*/5 * * * *", ) print(schedule_id) ``` -------------------------------- ### GET /v2/topics Source: https://upstash.com/docs/qstash/api-reference/url-groups/list-url-groups Retrieves a list of all URL groups associated with the account. ```APIDOC ## GET /v2/topics ### Description List all your URL Groups. ### Method GET ### Endpoint /v2/topics ### Response #### Success Response (200) - **Array** (URLGroup[]) - A list of URL group objects. #### Response Example [ { "name": "my-group", "createdAt": 1672531200000, "updatedAt": 1672531200000, "endpoints": [ { "name": "endpoint1", "url": "https://example.com" } ] } ] ``` -------------------------------- ### Run QStash Dev Server with Docker Source: https://upstash.com/docs/qstash/howto/local-development Pull and execute the QStash CLI image from the public AWS ECR repository. ```javascript // Pull the image docker pull public.ecr.aws/upstash/qstash:latest // Run the image docker run -p 8080:8080 public.ecr.aws/upstash/qstash:latest qstash dev ``` -------------------------------- ### POST /v2/queues/{queueName}/resume Source: https://upstash.com/docs/qstash/api-reference/queues/resume-queue Resumes a queue to start the delivery of enqueued messages. ```APIDOC ## POST /v2/queues/{queueName}/resume ### Description Resumes a queue to start the delivery of enqueued messages. ### Method POST ### Endpoint /v2/queues/{queueName}/resume ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to resume. ### Response #### Success Response (200) - Queue resumed successfully #### Error Response (400) - Queue name is invalid. Queue names can only contain alphanumeric characters, hyphens, periods, and underscores. ``` -------------------------------- ### List QStash events with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes the QStash client and retrieves a list of events. ```python from qstash import QStash client = QStash("") client.event.list() ``` -------------------------------- ### Create a URL group and add endpoints Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Initializes a QStash client and upserts a list of endpoints to a specified URL group. ```python from qstash import QStash client = QStash("") client.url_group.upsert_endpoints( url_group="my-url-group", endpoints=[ {"url": "https://my-endpoint-1"}, {"url": "https://my-endpoint-2"}, ], ) ``` -------------------------------- ### List URL Groups API Documentation Source: https://upstash.com/docs/qstash/overall/llms-txt Documentation block for the GET /v2/topics endpoint. ```APIDOC ## GET /v2/topics ### Description List all your URL Groups ### Method GET ### Endpoint /v2/topics ### Parameters #### Query Parameters - **qstash_token** (string) - Required - QStash authentication token passed as a query parameter ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **name** (string) - URL Group name - **createdAt** (integer) - Creation timestamp of URL Group in Unix milliseconds - **updatedAt** (integer) - Last update timestamp of URL Group in Unix milliseconds - **endpoints** (array) - List of endpoints associated with the URL Group - **name** (string) - The name of the endpoint - **url** (string) - The URL of the endpoint #### Response Example ```json { "example": "[ { "name": "my-url-group", "createdAt": 1678886400000, "updatedAt": 1678886400000, "endpoints": [ { "name": "my-endpoint", "url": "https://example.com/webhook" } ] } ]" } ``` ``` -------------------------------- ### Create a queue with parallelism Source: https://upstash.com/docs/qstash/sdks/py/examples/queues Initializes a QStash client and creates or updates a queue with a specified parallelism setting. ```python from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.upsert(queue_name, parallelism=2) print(client.queue.get(queue_name)) ``` -------------------------------- ### Start Background Job with QStash in Next.js Source: https://upstash.com/docs/qstash/overall/llms-txt A server-side route handler that publishes a JSON message to an email API endpoint using the QStash client. Requires a valid QStash token. ```typescript import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: "YOUR_TOKEN", }); export async function POST(request: Request) { const body = await request.json(); const users: string[] = body.users; // If you know the public URL of the email API, you can use it directly const rootDomain = request.url.split('/').slice(0, 3).join('/'); const emailAPIURL = `${rootDomain}/api/send-email`; // ie: https://yourapp.com/api/send-email // Tell QStash to start the background job. // For proper error handling, refer to the quick start. await qstashClient.publishJSON({ url: emailAPIURL, body: { users } }); return new Response("Job started", { status: 200 }); } ``` -------------------------------- ### List Flow Control Keys Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure for the /v2/flowControl endpoint. ```json [ { "flowControlKey": "my-key", "waitListSize": 0, "parallelismMax": 10, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ] ``` -------------------------------- ### Create Schedule JSON Payload Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON body for creating a schedule with a cron expression. ```json { "destination": "https://my-api...", "cron": "*/5 * * * *" } ``` -------------------------------- ### List All Schedules with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes the QStash client and retrieves a list of all configured schedules. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); ``` -------------------------------- ### Get Global Parallelism Data Source: https://upstash.com/docs/qstash/overall/llms-txt Returns the current global parallelism usage metrics. ```json { "parallelismMax": 100, "parallelismCount": 50 } ``` -------------------------------- ### GET /v2/flowControl Source: https://upstash.com/docs/qstash/api-reference/flow-control/list-flow-control-keys Retrieves a list of all flow control keys currently configured in the system. ```APIDOC ## GET /v2/flowControl ### Description List all Flow Control keys. ### Method GET ### Endpoint /v2/flowControl ### Response #### Success Response (200) - **Array** (FlowControlKey[]) - A list of flow control key objects. #### Response Example [ { "flowControlKey": "my-key", "waitListSize": 0, "parallelismMax": 10, "parallelismCount": 2, "rateMax": 100, "rateCount": 5, "ratePeriod": 60, "ratePeriodStart": 1672531200, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ] ``` -------------------------------- ### Publish Message to FIFO Queue Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON payload for enqueuing a message to a FIFO queue. ```json { "message": "Hello, World!" } ``` -------------------------------- ### Initialize Client (Development Mode) Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes the QStash client in development mode, automatically managing a local QStash dev server. ```APIDOC ## Initialize Client (Development Mode) ### Description Initializes the QStash client in development mode, automatically managing a local QStash dev server. ### Method Client Initialization ### Parameters #### Constructor Options - **devMode** (boolean) - Required - Set to `true` to enable development mode. ``` -------------------------------- ### GET /flowControl/{key} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current flow control settings for a specific key. ```APIDOC ## GET /flowControl/{key} ### Description Retrieves the current flow control settings for a specific key. ### Method GET ### Endpoint `/flowControl/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The unique identifier for the flow control key. ### Response #### Success Response (200) - **flowControlKey** (string) - The identifier for the flow control key. - **waitListSize** (integer) - The number of messages currently waiting in the queue. - **parallelismMax** (integer) - The maximum allowed concurrent messages. - **parallelismCount** (integer) - The current number of concurrent messages being processed. - **rateMax** (integer) - The maximum number of messages allowed within the rate period. - **rateCount** (integer) - The current number of messages processed within the rate period. - **ratePeriod** (integer) - The duration of the rate period in seconds. - **ratePeriodStart** (integer) - The timestamp when the current rate period started. - **isPaused** (boolean) - Indicates if delivery is currently paused for this key. - **isPinnedParallelism** (boolean) - Indicates if the parallelism setting is pinned. - **isPinnedRate** (boolean) - Indicates if the rate setting is pinned. ``` -------------------------------- ### Implement Main Webhook Handler Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go The main function sets up an HTTP server and handles signature verification using environment variables for signing keys. ```go func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() currentSigningKey := os.Getenv("QSTASH_CURRENT_SIGNING_KEY") nextSigningKey := os.Getenv("QSTASH_NEXT_SIGNING_KEY") tokenString := r.Header.Get("Upstash-Signature") body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = verify(body, tokenString, currentSigningKey) if err != nil { fmt.Printf("Unable to verify signature with current signing key: %v", err) err = verify(body, tokenString, nextSigningKey) } if err != nil { http.Error(w, err.Error(), http.StatusUnauthorized) return } // handle your business logic here w.WriteHeader(http.StatusOK) }) fmt.Println("listening on", port) err := http.ListenAndServe(":"+port, nil) if err != nil { panic(err) } } ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves the global parallelism settings and current usage count. ```python from qstash import QStash client = QStash("") info = client.flow_control.get_global_parallelism() print(info.parallelism_max) print(info.parallelism_count) ``` -------------------------------- ### Get Queue Details with SDKs Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves queue details using the TypeScript and Python SDKs. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() ``` ```python from qstash import QStash client = QStash("") client.queue.get("my-queue") ``` -------------------------------- ### Batch Message Request and Response Examples Source: https://upstash.com/docs/qstash/overall/llms-txt JSON structures for defining a batch of messages and the corresponding success response format. ```json [ { "destination": "myUrlGroup", "headers":{ "Upstash-Delay":"5s", "Upstash-Forward-Hello":"123456" }, "body": "Hello World" }, { "destination": "https://example.com/destination1", "headers":{ "Upstash-Delay":"7s", "Upstash-Forward-Hello":"789" } }, { "destination": "https://example.com/destination2", "headers":{ "Upstash-Delay":"9s", "Upstash-Forward-Hello":"again" } } ] ``` ```json [ [ { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint1.com" }, { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint2.com" } ], { "messageId": "msg_..." }, { "messageId": "msg_..." } ] ``` -------------------------------- ### Deploy Application Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Execute the deployment process to push the application to the Fly.io infrastructure. ```bash flyctl deploy ``` -------------------------------- ### Enqueue a message to a queue Source: https://upstash.com/docs/qstash/overall/llms-txt Examples for sending a JSON payload to a specific queue using different interfaces. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ 'https://qstash.upstash.io/v2/enqueue/my-queue/https://example.com' -d '{"message":"Hello, World!"}' ``` ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.enqueueJSON({ url: "https://example.com", body: { "Hello": "World" } }) ``` ```python from qstash import QStash client = QStash ("") client.message.enqueue_json( queue="my-queue", url="https://example.com", body={ "Hello": "World", }, ) ``` -------------------------------- ### Automate Schedule Creation with SDK Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Use the QStash Python SDK to programmatically create a scheduled job. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://YOUR_URL.vercel.app/api", cron="0 12 * * *", ) ``` -------------------------------- ### Get Global Parallelism Response Source: https://upstash.com/docs/qstash/overall/llms-txt JSON response showing global parallelism limits and current usage. ```json { "parallelismMax": 1000, "parallelismCount": 500 } ``` -------------------------------- ### Get a URL Group by name Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Retrieves details of a specific URL group by its name. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; const urlGroup = await urlGroups.get("urlGroupName"); console.log(urlGroup.name, urlGroup.endpoints); ``` -------------------------------- ### Get URL group by name Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Retrieves details of a specific URL group by its name. ```python from qstash import QStash client = QStash("") url_group = client.url_group.get("my-url-group") print(url_group.name, url_group.endpoints) ``` -------------------------------- ### Enable QStash Dev Mode via Environment Variables Source: https://upstash.com/docs/qstash/howto/local-development Set the QSTASH_DEV environment variable to true to automatically download and connect to the local dev server. ```bash QSTASH_DEV=true ``` -------------------------------- ### Get a schedule by ID Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Retrieves details of a specific schedule using its unique identifier. ```python from qstash import QStash client = QStash("") schedule = client.schedule.get("") print(schedule.cron) ``` -------------------------------- ### Get Flow Control Key Info with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches details for a specific flow control key. ```python from qstash import QStash client = QStash("") info = client.flow_control.get("USER_GIVEN_KEY") print(info) ``` -------------------------------- ### Scaffold Next.js Project Source: https://upstash.com/docs/qstash/overall/llms-txt Initialize a new Next.js project using the create-next-app CLI tool. ```bash npx create-next-app@latest qstash-bg-job ``` -------------------------------- ### Verify QStash Signatures in Python Source: https://upstash.com/docs/qstash/sdks/py/examples/receiver Initialize the Receiver with signing keys and use the verify method within a request handler to validate the request body and signature. ```python from qstash import Receiver receiver = Receiver( current_signing_key="YOUR_CURRENT_SIGNING_KEY", next_signing_key="YOUR_NEXT_SIGNING_KEY", ) # ... in your request handler signature, body = req.headers["Upstash-Signature"], req.body receiver.verify( body=body, signature=signature, url="YOUR-SITE-URL", ) ``` -------------------------------- ### GET /url_group/list Source: https://upstash.com/docs/qstash/overall/llms-txt Returns a list of all URL groups defined in the account. ```APIDOC ## GET /url_group/list ### Description Returns a list of all URL groups defined in the account. ### Method GET ### Endpoint /url_group/list ``` -------------------------------- ### Publish with Callback URLs Source: https://upstash.com/docs/qstash/sdks/py/examples/publish Configures success and failure callbacks for long-running functions and sets the HTTP method to GET. ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, callback="https://my-callback...", failure_callback="https://my-failure-callback...", method="GET", ) ``` -------------------------------- ### Retrieve Signing Keys in Python Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Fetches the current and next signing keys from the QStash client. ```python from qstash import QStash client = QStash("") signing_key = client.signing_key.get() print(signing_key.current, signing_key.next) ``` -------------------------------- ### Create or Overwrite Schedule Source: https://upstash.com/docs/qstash/overall/llms-txt Example request body for creating or overwriting a schedule with a user-defined schedule ID. ```APIDOC ## POST /schedules ### Description Creates or overwrites a schedule with a user-provided ID. ### Request Body - **destination** (string) - Required - The destination URL for the scheduled task. - **scheduleId** (string) - Required - A user-defined identifier for the schedule. - **cron** (string) - Required - The cron expression for the schedule timing. ### Request Example { "destination": "https://example.com", "scheduleId": "USER_PROVIDED_SCHEDULE_ID", "cron": "* * * * *" } ``` -------------------------------- ### GET /v2/flowControl/USER_GIVEN_KEY Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves information about a specific flow control key. ```APIDOC ## GET /v2/flowControl/USER_GIVEN_KEY ### Description Retrieves information about a specific flow control key. ### Method GET ### Endpoint `/v2/flowControl/USER_GIVEN_KEY` ### Headers - `Authorization`: Bearer ``` -------------------------------- ### List All Schedules with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves a list of all existing schedules using the QStash Python client. ```python from qstash import QStash client = QStash("") client.schedule.list() ``` -------------------------------- ### Retrieve all events with pagination in Python Source: https://upstash.com/docs/qstash/sdks/py/examples/events Uses a while loop and cursor to fetch all available events from QStash. Ensure you have your QSTASH-TOKEN ready for client initialization. ```python from qstash import QStash client = QStash("") all_events = [] cursor = None while True: res = client.event.list(cursor=cursor) all_events.extend(res.events) cursor = res.cursor if cursor is None: break ``` -------------------------------- ### Set QStash Secrets Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Configure the required signing keys as environment variables on the Fly.io platform. ```bash flyctl secrets set QSTASH_CURRENT_SIGNING_KEY=... flyctl secrets set QSTASH_NEXT_SIGNING_KEY=... ``` -------------------------------- ### Handle Flow Control Error Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response returned when a required flow-control key is missing. ```json { "example": { "error": "Flow control key is required." } } ``` -------------------------------- ### Get Flow Control Key Information with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve the current state and metrics for a specific flow control key using the QStash client. ```python from qstash import QStash client = QStash("") info = client.flow_control.get("USER_GIVEN_KEY") print(info) # FlowControlInfo( # key="USER_GIVEN_KEY", # wait_list_size=5, # parallelism_max=10, # parallelism_count=3, # rate_max=100, # rate_count=42, # rate_period=60, # rate_period_start=1708000000, # is_paused=False, # is_pinned_parallelism=False, # is_pinned_rate=False # ) ``` -------------------------------- ### QStash Success Response Source: https://upstash.com/docs/qstash/overall/llms-txt JSON response confirming successful configuration of flow-control key settings. ```json { "message": "Flow control key configuration pinned successfully." } ``` -------------------------------- ### Get Queue Information via API Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves queue details using a direct cURL request. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` ```json { "queueName": "my-queue", "parallelism": 5, "createdAt": "2023-10-27T10:00:00Z" } ``` -------------------------------- ### GET /v2/flowControl/{key} Source: https://upstash.com/docs/qstash/features/flowcontrol Retrieves the current state and metrics for a specific flow control key. ```APIDOC ## GET /v2/flowControl/{key} ### Description Returns the current state and metrics for one flow control key. ### Method GET ### Endpoint https://qstash.upstash.io/v2/flowControl/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The flow control key name. ### Response #### Success Response (200) - **flowControlKey** (string) - The flow control key name - **waitListSize** (number) - Number of messages currently waiting in the queue - **parallelismMax** (number) - Configured maximum concurrent messages - **parallelismCount** (number) - Number of messages currently running in parallel - **rateMax** (number) - Configured maximum messages per rate period - **rateCount** (number) - Number of messages dispatched in the current rate period - **ratePeriod** (number) - Rate period length in seconds - **ratePeriodStart** (number) - Unix timestamp when the current rate period started - **isPaused** (boolean) - Whether delivery is currently paused for this key - **isPinnedParallelism** (boolean) - Whether the parallelism configuration is pinned - **isPinnedRate** (boolean) - Whether the rate configuration is pinned ``` -------------------------------- ### Get queue details via Bash Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves queue configuration using a curl command with Bearer token authentication. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` -------------------------------- ### Get Queue Details with TypeScript SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the details of a specific queue using the QStash TypeScript SDK. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() ``` -------------------------------- ### GET /v2/topics/{urlGroupName} Source: https://upstash.com/docs/qstash/api-reference/url-groups/get-a-url-group Retrieve details of a specific URL Group. ```APIDOC ## GET /v2/topics/{urlGroupName} ### Description Retrieve details of a specific URL Group. ### Method GET ### Endpoint /v2/topics/{urlGroupName} ### Parameters #### Path Parameters - **urlGroupName** (string) - Required - The name of the URL Group to retrieve. ### Response #### Success Response (200) - **name** (string) - URL Group name - **createdAt** (integer) - Creation timestamp of URL Group in Unix milliseconds - **updatedAt** (integer) - Last update timestamp of URL Group in Unix milliseconds - **endpoints** (array) - List of endpoints associated with the group #### Error Response (404) - **error** (string) - Error message ``` -------------------------------- ### QStash Development Server Credentials Source: https://upstash.com/docs/qstash/overall/llms-txt Environment variables required to connect to a local QStash development server. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJkZWZhdWx0VXNlciIsIlBhc3N3b3JkIjoiZGVmYXVsdFBhc3N3b3JkIn0=" QSTASH_CURRENT_SIGNING_KEY="sig_7kYjw48mhY7kAjqNGcy6cr29RJ6r" QSTASH_NEXT_SIGNING_KEY="sig_5ZB6DVzB1wjE8S6rZ7eenA8Pdnhs" ``` -------------------------------- ### Publish Webhook with QStash Source: https://upstash.com/docs/qstash/overall/llms-txt Directly publishes a webhook request to QStash. ```bash https://qstash.upstash.io/v2/publish/https://example.com/api/webhook?qstash_token= ``` -------------------------------- ### Enqueue message with callbacks and redaction Source: https://upstash.com/docs/qstash/overall/llms-txt Example payload for POST /messages with failure callback and field redaction headers. ```json { "example": "POST /messages\nHeaders: {\n \"Upstash-Failure-Callback\": \"https://example.com/failed\",\n \"Upstash-Redact-Fields\": \"body,header[Authorization]\"\n}\nBody: {\n \"message\": \"Hello, QStash!\"\n}" } ``` -------------------------------- ### GET /v2/queues/{queueName} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current configuration and status of a specific queue, including its parallelism settings. ```APIDOC ## GET /v2/queues/{queueName} ### Description Retrieves the current configuration and status of a specific queue, including its parallelism settings. ### Method GET ### Endpoint https://qstash.upstash.io/v2/queues/{queueName} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to retrieve details for. ### Headers - **Authorization** (string) - Required - Bearer token for authentication. ``` -------------------------------- ### Configure ngrok authentication Source: https://upstash.com/docs/qstash/howto/local-tunnel Set your authentication token to connect your ngrok account to the CLI. ```bash ngrok config add-authtoken XXX ``` -------------------------------- ### Get Global Parallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve global parallelism data via the REST API using a bearer token. ```bash curl -X GET https://qstash.upstash.io/v2/globalParallelism \ -H "Authorization: Bearer " ``` -------------------------------- ### Handling Callbacks in Next.js Source: https://upstash.com/docs/qstash/features/callbacks Example of a Next.js API route to process callback requests, including signature verification and base64 decoding of the response body. ```javascript // pages/api/callback.js import { verifySignature } from "@upstash/qstash/nextjs"; function handler(req, res) { // responses from qstash are base64-encoded const decoded = atob(req.body.body); console.log(decoded); return res.status(200).end(); } export default verifySignature(handler); export const config = { api: { bodyParser: false, }, }; ``` -------------------------------- ### client.signing_key.get() Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Retrieves the current and next signing keys for the QStash client. ```APIDOC ## client.signing_key.get() ### Description Retrieves the current and next signing keys used to verify requests from QStash. ### Usage ```python from qstash import QStash client = QStash("") signing_key = client.signing_key.get() print(signing_key.current, signing_key.next) ``` ``` -------------------------------- ### Get global parallelism limits in TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current global parallelism configuration and usage statistics. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.getGlobalParallelism(); console.log(info); // { // parallelismMax: 500, // parallelismCount: 42 // } ``` -------------------------------- ### Create URL Group and Endpoints JSON Request Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON request body for creating a URL Group and adding endpoints using the QStash REST API. ```json { "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] } ``` -------------------------------- ### GET /messages/{messageId} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves a specific message using its unique identifier. ```APIDOC ## GET /messages/{messageId} ### Description Retrieves a specific message using its unique identifier. ### Method GET ### Endpoint /messages/{messageId} ### Parameters #### Path Parameters - **messageId** (string) - Required - The unique identifier of the message to retrieve. ### Response #### Success Response (200) - **message** (object) - The retrieved message object. - **id** (string) - The unique identifier of the message. - **content** (string) - The content of the message. - **contentType** (string) - The content type of the message. - **createdAt** (string) - The timestamp when the message was created. ``` -------------------------------- ### Retrieve Flow Control Settings Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure for current flow control settings including parallelism and rate limits. ```json { "flowControlKey": "USER_GIVEN_KEY", "waitListSize": 0, "parallelismMax": 10, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPaused": false, "isPinnedParallelism": false, "isPinnedRate": false } ``` -------------------------------- ### Configure Migration Mode Source: https://upstash.com/docs/qstash/howto/multi-region Set the QSTASH_REGION variable and provide credentials for each region to enable migration mode. ```bash # Migration mode configuration with US as primary QSTASH_REGION="US_EAST_1" US_EAST_1_QSTASH_URL="https://qstash-us-east-1.upstash.io" US_EAST_1_QSTASH_TOKEN="your_us_token" US_EAST_1_QSTASH_CURRENT_SIGNING_KEY="your_us_current_key" US_EAST_1_QSTASH_NEXT_SIGNING_KEY="your_us_next_key" EU_CENTRAL_1_QSTASH_URL="https://qstash-eu-central-1.upstash.io" EU_CENTRAL_1_QSTASH_TOKEN="your_eu_token" EU_CENTRAL_1_QSTASH_CURRENT_SIGNING_KEY="your_eu_current_key" EU_CENTRAL_1_QSTASH_NEXT_SIGNING_KEY="your_eu_next_key" ``` -------------------------------- ### List Schedules OpenAPI Definition Source: https://upstash.com/docs/qstash/api-reference/schedules/list-schedules The OpenAPI specification for the GET /v2/schedules endpoint and the associated Schedule schema. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/schedules: get: tags: - Schedules summary: List schedules description: List all schedules responses: '200': description: List of schedules content: application/json: schema: type: array items: $ref: '#/components/schemas/Schedule' components: schemas: Schedule: type: object required: - scheduleId - cron - destination - createdAt - method - isPaused properties: scheduleId: type: string description: Unique identifier for the schedule cron: type: string description: The cron expression used to schedule the message destination: type: string description: The destination URL or URL Group name createdAt: type: integer format: int64 description: The creation timestamp of the schedule in unix milliseconds method: type: string description: The HTTP method used for the scheduled message header: type: object additionalProperties: type: array items: type: string description: Map of header names to arrays of header values body: type: string description: The body of the scheduled message retries: type: integer description: The number of retries for the scheduled message delay: type: integer description: The delay in seconds before the scheduled message is sent callback: type: string description: The callback URL for the scheduled message failureCallback: type: string description: The failure callback URL for the scheduled message callerIp: type: string description: The IP address of the client that created the schedule isPaused: type: boolean description: Whether the schedule is paused flowControlKey: type: string description: The flow control key used for rate limiting parallelism: type: integer description: The parallelism value used for flow control rate: type: integer description: The rate value used for flow control period: type: integer description: The period value used for flow control retryDelayExpression: type: string description: The retry delay expression used for calculating retry delays label: type: string deprecated: true description: >- The label assigned to the scheduled message. Deprecated in favor of `labels`. labels: type: array items: type: string description: The list of labels assigned to the scheduled message. lastScheduleTime: type: integer format: int64 description: The last time the schedule was triggered in unix milliseconds nextScheduleTime: type: integer format: int64 description: The next scheduled trigger time in unix milliseconds lastScheduleStates: type: object description: The states of the last scheduled messages additionalProperties: type: string securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Execute QStash Binary Directly Source: https://upstash.com/docs/qstash/howto/local-development Run the extracted QStash executable directly from the command line. ```bash $ ./qstash dev ``` -------------------------------- ### Render Catalog Grid Component Source: https://upstash.com/docs/qstash/overall/getstarted A React component that filters and displays a list of guides and demos based on product, type, and featured status. ```javascript type: "guide" }, { title: "Crabbox", description: "Run your test suite in a Box from your local CLI.", href: "/box/guides/crabbox-setup", product: "box", type: "guide" }, { title: "Web Scraping with Playwright", description: "Scrape dynamic websites with Playwright.", href: "/box/guides/web-scraping-playwright", product: "box", type: "guide" }, { title: "E-commerce Order Fulfillment", description: "Durable order processing with Workflow.", href: "/workflow/examples/eCommerceOrderFulfillment", product: "workflow", type: "demo", lang: "typescript", featured: true }, { title: "Image Processing", description: "Fan-out image jobs with Workflow.", href: "/workflow/examples/imageProcessing", product: "workflow", type: "demo", lang: "typescript", featured: true }, { title: "Customer Onboarding", description: "Multi-step onboarding flow with delays.", href: "/workflow/examples/customerOnboarding", product: "workflow", type: "demo", lang: "typescript" }, { title: "Payment Retry", description: "Retry failed payments with backoff.", href: "/workflow/examples/paymentRetry", product: "workflow", type: "demo", lang: "typescript" }, { title: "Wait for Event", description: "Pause a workflow until an external event.", href: "/workflow/examples/waitForEvent", product: "workflow", type: "demo", lang: "typescript" }, { title: "Auth Webhook", description: "Handle auth webhooks durably.", href: "/workflow/examples/authWebhook", product: "workflow", type: "demo", lang: "typescript" }]; const matchesProduct = entry => !product || (Array.isArray(entry.product) ? entry.product.includes(product) : entry.product === product); const items = catalog.filter(entry => matchesProduct(entry) && (!type || entry.type === type) && (!featured || entry.featured) && (!search || entry.search)); const gridClass = "u-grid " + (cols >= 3 ? "u-grid--3" : "u-grid--2"); return ; }; ``` -------------------------------- ### GET /v2/schedules/{scheduleId} Source: https://upstash.com/docs/qstash/api-reference/schedules/get-a-schedule Retrieves the details of a specific schedule using its ID. ```APIDOC ## GET /v2/schedules/{scheduleId} ### Description Get details of a specific schedule. ### Method GET ### Endpoint /v2/schedules/{scheduleId} ### Parameters #### Path Parameters - **scheduleId** (string) - Required - The ID of the schedule to retrieve. ### Response #### Success Response (200) - **scheduleId** (string) - Unique identifier for the schedule - **cron** (string) - The cron expression used to schedule the message - **destination** (string) - The destination URL or URL Group name - **createdAt** (integer) - The creation timestamp of the schedule in unix milliseconds - **method** (string) - The HTTP method used for the scheduled message - **isPaused** (boolean) - Whether the schedule is paused - **header** (object) - Map of header names to arrays of header values - **body** (string) - The body of the scheduled message - **retries** (integer) - The number of retries for the scheduled message - **delay** (integer) - The delay in seconds before the scheduled message is sent - **callback** (string) - The callback URL for the scheduled message - **failureCallback** (string) - The failure callback URL for the scheduled message - **callerIp** (string) - The IP address of the client that created the schedule - **flowControlKey** (string) - The flow control key used for rate limiting - **parallelism** (integer) - The parallelism value used for flow control - **rate** (integer) - The rate value used for flow control - **period** (integer) - The period value used for flow control - **retryDelayExpression** (string) - The retry delay expression used for calculating retry delays - **labels** (array) - The list of labels assigned to the scheduled message - **lastScheduleTime** (integer) - The last time the schedule was triggered in unix milliseconds - **nextScheduleTime** (integer) - The next scheduled trigger time in unix milliseconds ``` -------------------------------- ### GET /v2/queues/{queueName} Source: https://upstash.com/docs/qstash/api-reference/queues/get-a-queue Retrieves the details of a specific queue, including its configuration and current lag status. ```APIDOC ## GET /v2/queues/{queueName} ### Description Get details of a specific queue. ### Method GET ### Endpoint /v2/queues/{queueName} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to retrieve. ### Response #### Success Response (200) - **name** (string) - The name of the queue. - **createdAt** (integer) - The creation timestamp of the queue in Unix milliseconds. - **updatedAt** (integer) - The last update timestamp of the queue in Unix milliseconds. - **parallelism** (integer) - The number of parallel consumers consuming from the queue. - **paused** (boolean) - Whether the queue is paused. - **lag** (integer) - The number of unprocessed messages that exist in the queue. ``` -------------------------------- ### Create Python Application Directory Source: https://upstash.com/docs/qstash/overall/llms-txt Commands to create and enter a new directory for a Python project. ```bash mkdir clean-db-cron ``` ```bash cd clean-db-cron ``` -------------------------------- ### GET /v2/dlq/{dlqId} Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Retrieves the details of a specific message from the DLQ by its ID. ```APIDOC ## GET /v2/dlq/{dlqId} ### Description Get a specific message from the DLQ. ### Method GET ### Endpoint /v2/dlq/{dlqId} ### Parameters #### Path Parameters - **dlqId** (string) - Required - The DLQ ID of the message you want to retrieve. ### Response #### Success Response (200) - **messageId** (string) - Unique identifier for the message - **url** (string) - The URL to which the message should be delivered. - **topicName** (string) - The URL Group (a.k.a. topic) name if this message was sent to a URL Group. - **endpointName** (string) - The endpoint name of the message if the endpoint is given a name within the URL group. - **method** (string) - The HTTP method to use for the message. - **header** (object) - The HTTP headers sent to your API. - **body** (string) - The body of the message if it is composed of utf8 chars only, empty otherwise. - **bodyBase64** (string) - The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. - **maxRetries** (integer) - The number of retries that should be attempted in case of delivery failure. - **notBefore** (integer) - The unix timestamp in milliseconds before which the message should not be delivered. - **createdAt** (integer) - The unix timestamp in milliseconds when the message was created. - **callback** (string) - The url where we send a callback each time the message is attempted to be delivered. - **failureCallback** (string) - The url where we send a callback to after the message is failed - **queueName** (string) - The name of the queue if the message is enqueued to a queue. - **scheduleId** (string) - The scheduleId of the message if the message is triggered by a schedule - **callerIP** (string) - IP address of the publisher of this message. - **label** (string) - The label of the message assigned by the user. - **labels** (array) - The labels of the message. ``` -------------------------------- ### Add endpoints to a URL Group Source: https://upstash.com/docs/qstash/howto/url-group-endpoint Use these examples to add multiple endpoints to an existing URL Group via the REST API or SDKs. ```bash curl -XPOST https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] }' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.addEndpoints({ name: "urlGroupName", endpoints: [ { name: "endpoint1", url: "https://example.com" }, { name: "endpoint2", url: "https://somewhere-else.com" }, ], }); ``` ```python from qstash import QStash client = QStash("") client.url_group.upsert_endpoints( url_group="url-group-name", endpoints=[ {"name": "endpoint1", "url": "https://example.com"}, {"name": "endpoint2", "url": "https://somewhere-else.com"}, ], ) ``` -------------------------------- ### Initialize QStash Receiver Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Create a new instance of the Receiver using environment variables. ```ts const receiver = new Receiver({ currentSigningKey: env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: env.QSTASH_NEXT_SIGNING_KEY, }); ``` -------------------------------- ### POST /v2/schedules Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule Creates a new schedule in QStash. ```APIDOC ## POST /v2/schedules ### Description Creates a new schedule. The request body contains the message to be scheduled. ### Method POST ### Endpoint /v2/schedules ### Request Body - **body** (text/plain, application/json, or application/octet-stream) - Required - The raw request message to be scheduled. ### Response #### Success Response (200) - **scheduleId** (string) - Unique identifier for the created schedule. #### Error Responses - **400** - Schedule ID is invalid (alphanumeric, hyphens, periods, and underscores only). - **412** - Exceeded the maximum number of schedules allowed. ``` -------------------------------- ### POST /v2/queue/{queueName}/resume Source: https://upstash.com/docs/qstash/overall/llms-txt Resumes a queue to start the delivery of enqueued messages. If the queue is already active, this action has no effect. ```APIDOC ## POST /v2/queue/{queueName}/resume ### Description Resumes a queue to start the delivery of enqueued messages. If the queue is already active, this action has no effect. Resuming a queue may take up to a minute. ### Method POST ### Endpoint /v2/queue/{queueName}/resume ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to resume. ### Request Example curl -X POST https://qstash.upstash.io/v2/queue/myQueue/resume \ -H "Authorization: Bearer " ``` -------------------------------- ### List Queues OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/queues/list-queues The OpenAPI definition for the GET /v2/queues endpoint, including the Queue schema definition. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/queues: get: tags: - Queues summary: List Queues description: List all your queues responses: '200': description: List of queues content: application/json: schema: type: array items: $ref: '#/components/schemas/Queue' components: schemas: Queue: type: object properties: name: type: string description: The name of the queue. createdAt: type: integer format: int64 description: The creation timestamp of the queue in Unix milliseconds updatedAt: type: integer format: int64 description: The last update timestamp of the queue in Unix milliseconds parallelism: type: integer description: The number of parallel consumers consuming from the queue paused: type: boolean description: Whether the queue is paused lag: type: integer description: The number of unprocessed messages that exist in the queue securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### GET /flowControl/global/parallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current and maximum allowed concurrent messages being processed globally. ```APIDOC ## GET /flowControl/global/parallelism ### Description Retrieves the current and maximum allowed concurrent messages being processed globally. ### Method GET ### Endpoint /flowControl/global/parallelism ### Response #### Success Response (200) - **parallelismMax** (integer) - The maximum allowed concurrent messages globally. - **parallelismCount** (integer) - The current number of concurrent messages being processed globally. #### Response Example { "parallelismMax": 1000, "parallelismCount": 500 } ``` -------------------------------- ### Retrieve URL Group Details via API Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches details for a specific URL group using a GET request. ```api ## GET /v2/topics/{urlGroupName} ### Description Retrieve details of a specific URL Group. ### Method GET ### Endpoint /v2/topics/{urlGroupName} ### Parameters #### Path Parameters - **urlGroupName** (string) - Required - The name of the URL Group to retrieve. ### Responses #### Success Response (200) - **name** (string) - URL Group name - **createdAt** (integer) - Creation timestamp of URL Group in Unix milliseconds - **updatedAt** (integer) - Last update timestamp of URL Group in Unix milliseconds - **endpoints** (array) - List of endpoints associated with the URL Group - **name** (string) - The name of the endpoint - **url** (string) - The URL of the endpoint #### Error Response (404) - **error** (string) - Error message ``` -------------------------------- ### GET /v2/flowControl Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve a list of all active flow control keys. This endpoint requires a valid QStash token provided as a query parameter. ```APIDOC ## GET /v2/flowControl ### Description Retrieve a list of all active flow control keys. ### Method GET ### Endpoint `/v2/flowControl` ### Parameters #### Query Parameters - **qstash_token** (string) - Required - Your QStash token. ### Response #### Success Response (200) - **flowControlKey** (string) - The unique key for flow control. - **waitListSize** (integer) - The number of messages waiting to be processed. - **parallelismMax** (integer) - The maximum allowed parallel processing. - **parallelismCount** (integer) - The current number of parallel processes. - **rateMax** (integer) - The maximum rate of messages per period. - **rateCount** (integer) - The current number of messages processed in the current rate period. - **ratePeriod** (integer) - The duration of the rate period in seconds. - **ratePeriodStart** (integer) - The timestamp when the current rate period started. - **isPinnedParallelism** (boolean) - Indicates if parallelism is pinned. - **isPinnedRate** (boolean) - Indicates if the rate is pinned. - **isPaused** (boolean) - Indicates if the flow control is paused. ### Response Example [ { "flowControlKey": "my-key", "waitListSize": 0, "parallelismMax": 10, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ] ``` -------------------------------- ### Get a single flow control key Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves the current status and configuration details for a specific flow control key. ```python from qstash import QStash client = QStash("") info = client.flow_control.get("USER_GIVEN_KEY") print(info.key) print(info.wait_list_size) print(info.parallelism_max) print(info.parallelism_count) print(info.rate_max) print(info.rate_count) print(info.rate_period) print(info.rate_period_start) print(info.is_paused) print(info.is_pinned_parallelism) print(info.is_pinned_rate) ``` -------------------------------- ### Next.js QStash Implementation Files Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs The core implementation files for the Next.js application, including the client-side UI, server-side action, and the protected API route for background tasks. ```tsx "use client" import { startBackgroundJob } from "@/app/actions"; import { useState } from "react"; export default function Home() { const [loading, setLoading] = useState(false); const [msg, setMsg] = useState(""); async function handleClick() { setLoading(true); const messageId = await startBackgroundJob(); if (messageId) { setMsg(`Started job with ID ${messageId}`); } else { setMsg("Failed to start background job"); } setLoading(false); } return (
{loading &&
Loading...
} {msg &&

{msg}

}
); } ``` ```ts "use server" import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }); export async function startBackgroundJob() { try { const response = await qstashClient.publishJSON({ "url": "https://qstash-bg-job.vercel.app/api/long-task", body: { "hello": "world" } }); return response.messageId; } catch (error) { console.error(error); return null; } } ``` ```ts import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" async function handler(request: Request) { const data = await request.json() for (let i = 0; i < 10; i++) { await fetch("https://firstqstashmessage.requestcatcher.com/test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, }) await new Promise((resolve) => setTimeout(resolve, 500)) } return Response.json({ success: true }) } export const POST = verifySignatureAppRouter(handler) ``` -------------------------------- ### GET /v2/flowControl/{key} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve detailed information about a specific flow control key, including its current state and configuration limits. ```APIDOC ## GET /v2/flowControl/{key} ### Description Retrieve detailed information about a specific flow control key, including its current state and configuration limits. Requires a valid QSTASH_TOKEN. ### Method GET ### Endpoint /v2/flowControl/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The flow control key to retrieve information for. ### Response #### Success Response (200) - **flowControlKey** (string) - The identifier for the flow control key. - **waitListSize** (integer) - The number of messages currently waiting in the queue. - **parallelismMax** (integer) - The maximum number of parallel requests allowed. - **parallelismCount** (integer) - The current number of parallel requests being processed. - **rateMax** (integer) - The maximum number of requests allowed within the rate period. - **rateCount** (integer) - The current number of requests made within the rate period. - **ratePeriod** (integer) - The duration of the rate period in seconds. - **ratePeriodStart** (integer) - The Unix timestamp when the current rate period started. - **isPaused** (boolean) - Indicates if the flow control is currently paused. - **isPinnedParallelism** (boolean) - Indicates if the parallelism limit is pinned. - **isPinnedRate** (boolean) - Indicates if the rate limit is pinned. ``` -------------------------------- ### client.schedule.create(destination, cron) Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a QStash schedule (cron job) using the QStash Python SDK. ```APIDOC ## client.schedule.create(destination, cron) ### Description Creates a QStash schedule (cron job) using the QStash Python SDK. ### Method client.schedule.create ### Parameters #### destination (string) - **destination** (string) - Required - The URL endpoint where the schedule will send messages. #### cron (string) - **cron** (string) - Required - The cron expression defining the schedule's timing. ### Request Example ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://YOUR_URL.vercel.app/api", cron="0 12 * * *", ) ``` ### Response #### Success Response - **scheduleId** (string) - The unique identifier for the created schedule. #### Response Example ```json { "scheduleId": "sched_..." } ``` ``` -------------------------------- ### Verify Signature with QStash SDK (Golang) Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes a receiver with signing keys and verifies the Upstash-Signature header in a request handler. ```go import "github.com/qstash/qstash-go" receiver := qstash.NewReceiver("", "NEXT_SIGNING_KEY") // ... in your request handler signature := req.Header.Get("Upstash-Signature") body, err := io.ReadAll(req.Body) // handle err err := receiver.Verify(qstash.VerifyOptions{ Signature: signature, Body: string(body), Url: "YOUR-SITE-URL", // optional }) // handle err ``` -------------------------------- ### Configure QStash environment variables Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Required environment variables for QStash authentication and signature verification. ```bash # Copy all three from your QStash dashboard QSTASH_TOKEN= QSTASH_CURRENT_SIGNING_KEY= QSTASH_NEXT_SIGNING_KEY= ``` -------------------------------- ### Redact message fields during publication Source: https://upstash.com/docs/qstash/howto/redact-fields Examples showing how to configure redaction for message bodies and specific headers across different interfaces. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, redact: { body: true, header: ["Authorization"] // or `header: true` to redact all headers }, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, redact={ "body": True, "header": ["Authorization"] // or `header: True` to redact all headers }, ) ``` ```bash curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-Type: application/json" \ -H "Upstash-Redact-Fields: body, header[Authorization]" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ``` -------------------------------- ### GET /v1/flowcontrol/{key} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves detailed information about a specific flow control key, including its current state and configuration limits. ```APIDOC ## GET /v1/flowcontrol/{key} ### Description Retrieves detailed information about a specific flow control key, including its current state and configuration limits. ### Method GET ### Endpoint `/v1/flowcontrol/{key}` ### Parameters #### Path Parameters - `key` (string) - Required - The flow control key identifier. ### Response #### Success Response (200) - `key` (string) - The flow control key. - `wait_list_size` (number) - Current size of the wait list. - `parallelism_max` (number) - Maximum allowed parallelism. - `parallelism_count` (number) - Current parallelism count. - `rate_max` (number) - Maximum allowed rate. - `rate_count` (number) - Current rate count. - `rate_period` (number) - Rate period duration. - `rate_period_start` (number) - Start timestamp of the rate period. - `is_paused` (boolean) - Whether the key is currently paused. - `is_pinned_parallelism` (boolean) - Whether parallelism is pinned. - `is_pinned_rate` (boolean) - Whether rate is pinned. ``` -------------------------------- ### Import Dependencies Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Required imports for the main application file. ```go package main import ( "crypto/sha256" "encoding/base64" "fmt" "github.com/golang-jwt/jwt/v4" "io" "net/http" "os" "time" ) ``` -------------------------------- ### Get a specific DLQ message Source: https://upstash.com/docs/qstash/sdks/py/examples/dlq Retrieves a single message from the DLQ by its unique identifier. ```python from qstash import QStash client = QStash("") msg = client.dlq.get("") ``` -------------------------------- ### Configure QStash Schedule Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Configuration details for setting up a cron job in the QStash dashboard. ```text URL: https://your-vercel-app.vercel.app/api Type: Schedule Every: every day at midnight (feel free to customize) ``` -------------------------------- ### OpenAPI Specification for Get DLQ Message Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Defines the endpoint path, parameters, and response schemas for retrieving a message from the DLQ. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/dlq/{dlqId}: get: tags: - DLQ summary: Get a DLQ message description: Get a specific message from the DLQ parameters: - name: dlqId in: path required: true schema: type: string description: | The DLQ ID of the message you want to retrieve. responses: '200': description: DLQ message details content: application/json: schema: $ref: '#/components/schemas/DLQMessage' '404': description: > If the message is not found in the DLQ, (either is has been removed by you, or automatically), the endpoint returns a 404 status code. content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: DLQMessage: type: object properties: messageId: type: string description: Unique identifier for the message url: type: string description: The URL to which the message should be delivered. topicName: type: string description: >- The URL Group (a.k.a. topic) name if this message was sent to a URL Group. endpointName: type: string description: >- The endpoint name of the message if the endpoint is given a name within the URL group. method: type: string description: The HTTP method to use for the message. header: type: object additionalProperties: type: array items: type: string description: The HTTP headers sent to your API. body: type: string description: >- The body of the message if it is composed of utf8 chars only, empty otherwise. bodyBase64: type: string description: >- The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. maxRetries: type: integer description: >- The number of retries that should be attempted in case of delivery failure. notBefore: type: integer format: int64 description: >- The unix timestamp in milliseconds before which the message should not be delivered. createdAt: type: integer format: int64 description: The unix timestamp in milliseconds when the message was created. callback: type: string description: >- The url where we send a callback each time the message is attempted to be delivered. failureCallback: type: string description: The url where we send a callback to after the message is failed queueName: type: string description: The name of the queue if the message is enqueued to a queue. scheduleId: type: string description: >- The scheduleId of the message if the message is triggered by a schedule callerIP: type: string description: IP address of the publisher of this message. label: type: string deprecated: true description: >- The label of the message assigned by the user. Deprecated in favor of `labels`. labels: type: array items: type: string ``` -------------------------------- ### Enable Local Development Mode Source: https://upstash.com/docs/qstash/sdks/ts/gettingstarted Use devMode to automatically manage a local QStash server without requiring tokens or signing keys. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ devMode: true }); ``` -------------------------------- ### OpenAPI Specification for Get a URL Group Source: https://upstash.com/docs/qstash/api-reference/url-groups/get-a-url-group Defines the endpoint path, parameters, and response schemas for retrieving URL group details. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/topics/{urlGroupName}: get: tags: - URL Groups summary: Get a URL Group description: Retrieve details of a specific URL Group parameters: - name: urlGroupName in: path required: true schema: type: string description: The name of the URL Group to retrieve. responses: '200': description: '' content: application/json: schema: $ref: '#/components/schemas/URLGroup' '404': description: URL Group not found content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: URLGroup: type: object properties: name: type: string description: URL Group name createdAt: type: integer description: Creation timestamp of URL Group in Unix milliseconds updatedAt: type: integer description: Last update timestamp of URL Group in Unix milliseconds endpoints: type: array items: $ref: '#/components/schemas/Endpoint' Error: type: object required: - error properties: error: type: string description: Error message Endpoint: type: object properties: name: type: string description: The name of the endpoint url: type: string description: The URL of the endpoint securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### OpenAPI Specification for List Logs Source: https://upstash.com/docs/qstash/api-reference/logs/list-logs Defines the GET /v2/logs endpoint, including query parameters for pagination and filtering by message state, ID, and timestamps. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/logs: get: tags: - Logs summary: List Logs description: Paginate through logs of published messages parameters: - name: cursor in: query schema: type: string description: By providing a cursor you can paginate through all of the logs - name: messageId in: query schema: type: string description: Filter logs by message ID - name: state in: query schema: type: string enum: - CREATED - ACTIVE - RETRY - ERROR - IN_PROGRESS - DELIVERED - CANCEL_REQUESTED - CANCELLED description: "Filter logs by message state\n\n|Value\t|Description|\n|-------|------------|\n| CREATED\t|The message has been accepted and stored in QStash|\n| ACTIVE\t|The task is currently being processed by a worker.|\n| RETRY\t|The task has been scheduled to retry.|\n| ERROR\t|The execution threw an error and the task is waiting to be retried or failed.|\n| IN_PROGRESS\t|The task is in one of ACTIVE, RETRY or ERROR state.|\n| DELIVERED\t|The message was successfully delivered.|\n| FAILED\t|The task has errored too many times or encountered an error that it cannot recover from.|\n| CANCEL_REQUESTED\t|The cancel request from the user is recorded.|\n| CANCELLED\t|The cancel request from the user is honored.|\n" - name: url in: query schema: type: string description: Filter logs by destination URL - name: topicName in: query schema: type: string description: Filter logs by URL Group name - name: scheduleId in: query schema: type: string description: Filter logs by schedule ID - name: queueName in: query schema: type: string description: Filter logs by queue name - name: fromDate in: query schema: type: integer format: int64 description: >- Filter logs by starting date, in milliseconds (Unix timestamp). This is inclusive. - name: toDate in: query schema: type: integer format: int64 description: >- Filter logs by ending date, in milliseconds (Unix timestamp). This is inclusive. - name: count in: query schema: type: integer default: 100 maximum: 100 description: The number of log entries to return. - name: label in: query schema: type: array items: type: string style: form explode: true description: > Filter logs by label. Supports multi-value filtering. You can pass multiple values to match messages with any of the given labels (OR logic). Examples: - `label=my_label` - `label=label_1&label=label_2` responses: '200': description: List of logs content: application/json: schema: type: object properties: cursor: type: string description: > A cursor which you can use in subsequent requests to paginate through all logs. ``` -------------------------------- ### Configure Migration Mode Environment Variables Source: https://upstash.com/docs/qstash/overall/llms-txt Sets environment variables to enable migration mode and configure multi-region support for US and EU regions. ```bash QSTASH_REGION="US_EAST_1" US_EAST_1_QSTASH_URL="https://qstash-us-east-1.upstash.io" US_EAST_1_QSTASH_TOKEN="your_us_token" US_EAST_1_QSTASH_CURRENT_SIGNING_KEY="your_us_current_key" US_EAST_1_QSTASH_NEXT_SIGNING_KEY="your_us_next_key" EU_CENTRAL_1_QSTASH_URL="https://qstash-eu-central-1.upstash.io" EU_CENTRAL_1_QSTASH_TOKEN="your_eu_token" EU_CENTRAL_1_QSTASH_CURRENT_SIGNING_KEY="your_eu_current_key" EU_CENTRAL_1_QSTASH_NEXT_SIGNING_KEY="your_eu_next_key" ``` -------------------------------- ### Implement Lambda Handler Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python The main entry point that retrieves signing keys from environment variables and triggers signature verification. ```python def lambda_handler(event, context): # parse the inputs current_signing_key = os.environ['QSTASH_CURRENT_SIGNING_KEY'] next_signing_key = os.environ['QSTASH_NEXT_SIGNING_KEY'] headers = event['headers'] signature = headers['upstash-signature'] url = "https://{}{}".format(event["requestContext"]["domainName"], event["rawPath"]) body = None if 'body' in event: body = event['body'] # check verification now try: verify(signature, current_signing_key, body, url) except Exception as e: print("Failed to verify signature with current signing key:", e) try: verify(signature, next_signing_key, body, url) except Exception as e2: return { "statusCode": 400, "body": json.dumps({ "error": str(e2), }), } # Your logic here... return { "statusCode": 200, "body": json.dumps({ "message": "ok", }), } ``` -------------------------------- ### Implement Background Job Workflow in Next.js Source: https://upstash.com/docs/qstash/features/background-jobs This set of snippets demonstrates the three-part workflow: triggering the job from the client, scheduling it via the QStash client, and the worker endpoint that executes the task. ```tsx "use client" export default function Home() { async function handleClick() { // Send a request to our server to start the background job. // For proper error handling, refer to the quick start. // Note: This can also be a server action instead of a route handler await fetch("/api/start-email-job", { method: "POST", body: JSON.stringify({ users: ["a@gmail.com", "b@gmail.com", "c.gmail.com"] }), }) } return (
); } ``` ```typescript import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: "YOUR_TOKEN", }); export async function POST(request: Request) { const body = await request.json(); const users: string[] = body.users; // If you know the public URL of the email API, you can use it directly const rootDomain = request.url.split('/').slice(0, 3).join('/'); const emailAPIURL = `${rootDomain}/api/send-email`; // ie: https://yourapp.com/api/send-email // Tell QStash to start the background job. // For proper error handling, refer to the quick start. await qstashClient.publishJSON({ url: emailAPIURL, body: { users } }); return new Response("Job started", { status: 200 }); } ``` ```typescript // This is a public API endpoint that will be invoked by QStash. // It contains the logic for the background job and may take a long time to execute. import { sendEmail } from "your-email-library"; export async function POST(request: Request) { const body = await request.json(); const users: string[] = body.users; // Send emails to the users for (const user of users) { await sendEmail(user); } return new Response("Job started", { status: 200 }); } ``` -------------------------------- ### Create URL Group and Add Endpoints via API Source: https://upstash.com/docs/qstash/overall/llms-txt Use the QStash REST API to create a URL group and register multiple endpoints. ```bash curl -XPOST https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] }' ``` -------------------------------- ### Retrieve Message Status Response Source: https://upstash.com/docs/qstash/overall/llms-txt Example JSON response structure for a message retrieval request. ```json { "messageId": "msg_12345", "deduplicated": false } ``` -------------------------------- ### GET /v1/flowcontrol/global-parallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current global parallelism settings, showing the maximum allowed concurrent messages across all flow control keys. ```APIDOC ## GET /v1/flowcontrol/global-parallelism ### Description Retrieves the current global parallelism settings, showing the maximum allowed concurrent messages across all flow control keys. ### Method GET ### Endpoint /v1/flowcontrol/global-parallelism ### Response #### Success Response (200) - **parallelism_max** (integer) - The maximum allowed concurrent messages globally. - **parallelism_count** (integer) - The current count of active concurrent messages. ``` -------------------------------- ### Send Chat Completion Requests in Batches with JavaScript Source: https://upstash.com/docs/qstash/overall/llms-txt Demonstrates how to send multiple chat completion requests concurrently using QStash's batching functionality. ```javascript import { Client, upstash } from "@upstash/qstash"; const client = new Client({ token: "", }); const result = await client.batchJSON([ { api: { name: "llm", provider: openai({ token: "_OPEN_AI_TOKEN_" }) }, body: { ... }, callback: "https://abc.requestcatcher.com", }, ... ]); console.log(result); ``` -------------------------------- ### Verify Incoming Requests with Region Support Source: https://upstash.com/docs/qstash/howto/multi-region Pass the upstash-region header to the verify method to ensure correct signing key selection in multi-region setups. ```typescript import { Receiver } from "@upstash/qstash"; // Initialize receiver (works in both modes) const receiver = new Receiver(); // Verify the incoming request await receiver.verify({ signature: request.headers.get("upstash-signature")!, body: await request.text(), // Pass the region header for multi-region support upstashRegion: request.headers.get("upstash-region") ?? undefined, }); ``` -------------------------------- ### Verify QStash Signatures in TypeScript Source: https://upstash.com/docs/qstash/sdks/ts/examples/receiver Initialize the Receiver with signing keys and use the verify method to validate incoming request signatures. ```typescript import { Receiver } from "@upstash/qstash"; const receiver = new Receiver({ currentSigningKey: "YOUR_CURRENT_SIGNING_KEY", nextSigningKey: "YOUR_NEXT_SIGNING_KEY", }); // ... in your request handler const signature = req.headers["Upstash-Signature"]; const body = req.body; const isValid = await receiver.verify({ body, signature, url: "YOUR-SITE-URL", }); ``` -------------------------------- ### GET /v2/flowControl/{flowControlKey} Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-flow-control-key Retrieves the details of a specific Flow Control key, including its current wait list size, parallelism settings, and rate limit status. ```APIDOC ## GET /v2/flowControl/{flowControlKey} ### Description Get details of a specific Flow Control key. ### Method GET ### Endpoint /v2/flowControl/{flowControlKey} ### Parameters #### Path Parameters - **flowControlKey** (string) - Required - The Flow Control key to retrieve ### Response #### Success Response (200) - **flowControlKey** (string) - The flow control key name - **waitListSize** (integer) - The number of messages waiting due to flow control configuration. - **parallelismMax** (integer) - The configured maximum number of messages allowed to run concurrently, if parallelism is set. - **parallelismCount** (integer) - The current number of messages running in parallel. - **rateMax** (integer) - The configured maximum number of messages allowed per rate period, if rate limiting is set. - **rateCount** (integer) - The number of messages dispatched in the current rate period. - **ratePeriod** (integer) - The length of the rate period in seconds. - **ratePeriodStart** (integer) - Unix timestamp (seconds) when the current rate period started. - **isPinnedParallelism** (boolean) - True if the flow-control key has a pinned parallelism configuration. - **isPinnedRate** (boolean) - True if the flow-control key has a pinned rate configuration. - **isPaused** (boolean) - True if the delivery of messages associated with the flow-control key is paused. #### Error Response (404) - **error** (string) - Error message ``` -------------------------------- ### POST /publish Source: https://upstash.com/docs/qstash/overall/llms-txt Use this endpoint to send a single chat completion request to an OpenAI-compatible provider via QStash. ```APIDOC ## POST /publish ### Description Use these examples to send a single chat completion request to an OpenAI-compatible provider via QStash. ### Method POST ### Endpoint /publish ### Request Body - **api** (object) - Required - Specifies the API details for the LLM provider. - **name** (string) - Required - The name of the API, e.g., "llm". - **provider** (object) - Required - Details of the LLM provider. - **token** (string) - Required - The API token for the LLM provider (e.g., OpenAI API key). - **body** (object) - Required - The request body for the chat completion API. - **model** (string) - Required - The LLM model to use (e.g., "gpt-3.5-turbo"). - **messages** (array) - Required - An array of message objects for the chat. - **role** (string) - Required - The role of the message sender (e.g., "user"). - **content** (string) - Required - The content of the message. - **callback** (string) - Optional - A URL to send the response to. ``` -------------------------------- ### List URL Groups API Definition Source: https://upstash.com/docs/qstash/overall/llms-txt Describes the GET endpoint for retrieving all URL groups. ```APIDOC ## GET /url_group/list ### Description Returns a list of all URL groups defined in the account. ``` -------------------------------- ### Batch Publish Messages with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Send messages to a URL Group and a direct URL using the QStash Python client. ```python from qstash import QStash client = QStash("") client.message.batch_json( [ {"url_group": "my-url-group"}, {"url": "https://example.com/destination2"}, ] ) ``` -------------------------------- ### OpenAPI Specification for Listing DLQ Messages Source: https://upstash.com/docs/qstash/api-reference/dlq/list-dlq-messages Defines the GET /v2/dlq endpoint, including available query parameters for filtering by message ID, URL, topic, schedule, queue, date range, response status, IP, and labels. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/dlq: get: tags: - DLQ summary: List DLQ messages description: List and paginate through all messages currently in the DLQ parameters: - name: cursor in: query schema: type: string description: >- By providing a cursor you can paginate through all of the messages in the DLQ - name: messageId in: query schema: type: string description: Filter DLQ messages by message ID - name: url in: query schema: type: array items: type: string description: Filter DLQ messages by destination URL. Supports multiple values. - name: topicName in: query schema: type: array items: type: string description: Filter DLQ messages by URL Group name. Supports multiple values. - name: scheduleId in: query schema: type: array items: type: string description: Filter DLQ messages by schedule ID. Supports multiple values. - name: queueName in: query schema: type: array items: type: string description: Filter DLQ messages by queue name. Supports multiple values. - name: fromDate in: query schema: type: integer format: int64 description: >- Filter DLQ messages by starting date, in milliseconds (Unix timestamp). This is inclusive. - name: toDate in: query schema: type: integer format: int64 description: >- Filter DLQ messages by ending date, in milliseconds (Unix timestamp). This is inclusive. - name: responseStatus in: query schema: type: array items: type: integer description: >- Filter DLQ messages by HTTP response status code of the last delivery attempt. Supports multiple values. - name: callerIp in: query schema: type: array items: type: string description: >- Filter DLQ messages by IP address of the publisher. Supports multiple values. - name: label in: query schema: type: array items: type: string description: > Filter DLQ messages by label. Supports multiple values. You can pass multiple values to match messages with any of the given labels (OR logic). Examples: - `label=my_label` - `label=label_1&label=label_2` - `label=label_1,label_2` - name: count in: query schema: type: integer default: 100 maximum: 100 description: The number of messages to return. responses: '200': description: List of DLQ messages content: application/json: schema: type: object properties: cursor: type: string description: > A cursor which you can use in subsequent requests to paginate through all messages. ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the global maximum and current parallelism counts for message processing. ```APIDOC ## Get global parallelism ### Description Retrieves the global maximum and current parallelism counts for message processing. ### Method Signature `client.flow_control.get_global_parallelism()` ### Response #### Success Response (200) - **parallelism_max** (int) - The global maximum number of parallel messages allowed. - **parallelism_count** (int) - The current global number of parallel messages being processed. ``` -------------------------------- ### Verify Signature (Go SDK) Source: https://upstash.com/docs/qstash/overall/llms-txt Implement signature verification in Go using the qstash-go SDK to validate incoming requests. ```APIDOC import "github.com/qstash/qstash-go" receiver := qstash.NewReceiver("", "NEXT_SIGNING_KEY") // ... in your request handler signature := req.Header.Get("Upstash-Signature") body, err := io.ReadAll(req.Body) err := receiver.Verify(qstash.VerifyOptions{ Signature: signature, Body: string(body), Url: "YOUR-SITE-URL", // optional }) ``` -------------------------------- ### Authenticate with Query Parameter Source: https://upstash.com/docs/qstash/api/authentication Use the qstash_token query parameter when setting request headers is not feasible. ```bash curl https://qstash.upstash.io/v2/publish/...?qstash_token= ``` -------------------------------- ### Configure QStash Client for Dev Mode Source: https://upstash.com/docs/qstash/howto/local-development Explicitly enable dev mode in the QStash client instance. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ devMode: true }); await client.publishJSON({ url: "https://example.com/webhook", body: { hello: "world" }, }); ``` -------------------------------- ### Deploy AWS CDK Stack Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Execute this command in the terminal to deploy the defined infrastructure to AWS. ```bash cdk deploy ``` -------------------------------- ### GET /v2/messages/{messageId} Source: https://upstash.com/docs/qstash/api-reference/messages/get-a-message Retrieve details of a specific message using its unique message identifier. ```APIDOC ## GET /v2/messages/{messageId} ### Description Retrieve details of a specific message. ### Method GET ### Endpoint /v2/messages/{messageId} ### Parameters #### Path Parameters - **messageId** (string) - Required - The identifier of the message to retrieve. ### Response #### Success Response (200) - **messageId** (string) - Unique identifier for the message - **url** (string) - The URL to which the message should be delivered. - **topicName** (string) - The URL Group (a.k.a. topic) name if this message was sent to a URL Group. - **endpointName** (string) - The endpoint name of the message if the endpoint is given a name within the URL group. - **method** (string) - The HTTP method to use for the message. - **header** (object) - The HTTP headers sent to your API. - **body** (string) - The body of the message if it is composed of utf8 chars only, empty otherwise. - **bodyBase64** (string) - The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. - **maxRetries** (integer) - The number of retries that should be attempted in case of delivery failure. - **notBefore** (integer) - The unix timestamp in milliseconds before which the message should not be delivered. - **createdAt** (integer) - The unix timestamp in milliseconds when the message was created. - **callback** (string) - The url where we send a callback each time the message is attempted to be delivered. - **failureCallback** (string) - The url where we send a callback to after the message is failed - **queueName** (string) - The name of the queue if the message is enqueued to a queue. - **scheduleId** (string) - The scheduleId of the message if the message is triggered by a schedule - **callerIP** (string) - IP address of the publisher of this message. - **label** (string) - The label of the message assigned by the user. - **labels** (array) - The list of labels assigned to the message by the user. - **flowControlKey** (string) - The flow control key used for rate limiting. #### Error Response (404) - Message not found ``` -------------------------------- ### GET /v2/globalParallelism Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-global-parallelism Returns the current global parallelism usage across all flow control keys. ```APIDOC ## GET /v2/globalParallelism ### Description Returns the current global parallelism usage across all flow control keys. ### Method GET ### Endpoint /v2/globalParallelism ### Response #### Success Response (200) - **parallelismMax** (integer) - The configured maximum global parallelism - **parallelismCount** (integer) - The current number of messages running globally in parallel ``` -------------------------------- ### Schedule Messages with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Create a recurring schedule using the QStash Python client. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="0 0 * * *", ) # Async version is also available ``` -------------------------------- ### Create Cloudflare Worker Project Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Initialize a new Cloudflare Worker project using the C3 CLI tool. ```shell npm create cloudflare@latest ``` ```shell yarn create cloudflare@latest ``` -------------------------------- ### Create URL Group and Add Endpoints via cURL Source: https://upstash.com/docs/qstash/overall/llms-txt Use this command to define a URL group and associate multiple endpoints with it. Replace with your valid QStash authentication token. ```bash curl -XPOST https://qstash.upstash.io/v2/topics/:urlGroupName \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] \ }' ``` -------------------------------- ### Create Schedule to URL Group (Python) Source: https://upstash.com/docs/qstash/overall/llms-txt Create a schedule targeting a URL group that executes every minute. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="my-url-group", cron="0 * * * *", ); ``` -------------------------------- ### Handling Daily Rate Limit Error Source: https://upstash.com/docs/qstash/api/api-ratelimiting Demonstrates how to catch and handle the QstashDailyRatelimitError when a daily rate limit is exceeded. ```APIDOC import { QstashDailyRatelimitError } from "@upstash/qstash"; try { const result = await client.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); } catch (error) { if (error instanceof QstashDailyRatelimitError) { console.log("Daily rate limit exceeded. Retry after:", error.reset); } else { console.error("An unexpected error occurred:", error); } } ``` -------------------------------- ### GET /v2/dlq/{dlqId} Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches a specific message from the Dead Letter Queue using its DLQ ID. ```APIDOC ## GET /v2/dlq/{dlqId} ### Description Get a specific message from the DLQ. ### Method GET ### Endpoint /v2/dlq/{dlqId} ### Parameters #### Path Parameters - **dlqId** (string) - Required - The DLQ ID of the message you want to retrieve. ### Responses #### Success Response (200) - **messageId** (string) - Unique identifier for the message - **url** (string) - The URL to which the message should be delivered. - **topicName** (string) - The URL Group (a.k.a. topic) name if this message was sent to a URL Group. - **endpointName** (string) - The endpoint name of the message if the endpoint is given a name within the URL group. - **method** (string) - The HTTP method to use for the message. - **header** (object) - The HTTP headers sent to your API. - **body** (string) - The body of the message if it is composed of utf8 chars only, empty otherwise. - **bodyBase64** (string) - The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. - **maxRetries** (integer) - The number of retries that should be attempted in case of delivery failure. - **notBefore** (integer) - The unix timestamp in milliseconds before which the message should not be delivered. - **createdAt** (integer) - The unix timestamp in milliseconds when the message was created. - **callback** (string) - The url where we send a callback each time the message is attempted to be delivered. - **failureCallback** (string) - The url where we send a callback to after the message is failed - **queueName** (string) - The name of the queue if the message is enqueued to a queue. - **scheduleId** (string) - The scheduleId of the message if the message is triggered by a schedule - **callerIP** (string) - IP address of the publisher of this message. - **label** (string) - The label of the message assigned by the user. Deprecated in favor of `labels`. - **labels** (array) - Array of strings representing message labels. #### Error Response (404) - **message** (string) - Error message indicating the message was not found. ### Response Example (200) { "messageId": "msg_abc123", "url": "https://example.com/webhook", "topicName": "my-topic", "endpointName": "my-endpoint", "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"key\": \"value\"}", "bodyBase64": "", "maxRetries": 3, "notBefore": 1678886400000, "createdAt": 1678886300000, "callback": "https://example.com/callback", "failureCallback": "https://example.com/failure-callback", "queueName": "my-queue", "scheduleId": "sch_xyz789", "callerIP": "192.168.1.1", "labels": ["important"] } ``` -------------------------------- ### Publish Message with Callback using cURL Source: https://upstash.com/docs/qstash/overall/llms-txt Sends a POST request to QStash with a callback header for delivery status tracking. ```bash curl -X POST \ https://qstash.upstash.io/v2/publish/https://my-api... \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Callback: ' \ -d '{ "hello": "world" }' ``` -------------------------------- ### Send Batch Messages with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Uses the QStash Python client to send multiple messages with varying configurations like delays, bodies, and headers. ```python from qstash import QStash client = QStash("") client.message.batch_json( [ { "url_group": "my-url-group", "delay": "5s", "body": {"hello": "world"}, "headers": {"random": "header"}, }, { "url": "https://example.com/destination1", "delay": "1m", }, { "url": "https://example.com/destination2", "body": {"hello": "again"}, }, ] ) ``` -------------------------------- ### Test user environment variables Source: https://upstash.com/docs/qstash/howto/local-development Credentials and signing keys for local development test users. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJkZWZhdWx0VXNlciIsIlBhc3N3b3JkIjoiZGVmYXVsdFBhc3N3b3JkIn0=" QSTASH_CURRENT_SIGNING_KEY="sig_7kYjw48mhY7kAjqNGcy6cr29RJ6r" QSTASH_NEXT_SIGNING_KEY="sig_5ZB6DVzB1wjE8S6rZ7eenA8Pdnhs" ``` ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjEiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_7GVPjvuwsfqF65iC8fSrs1dfYruM" QSTASH_NEXT_SIGNING_KEY="sig_5NoELc3EFnZn4DVS5bDs2Nk4b7Ua" ``` ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjIiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_6jWGaWRxHsw4vMSPJprXadyvrybF" QSTASH_NEXT_SIGNING_KEY="sig_7qHbvhmahe5GwfePDiS5Lg3pi6Qx" ``` ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjMiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_5T8FcSsynBjn9mMLBsXhpacRovJf" QSTASH_NEXT_SIGNING_KEY="sig_7GFR4YaDshFcqsxWRZpRB161jguD" ``` -------------------------------- ### Create Public HTTP Endpoint Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Expose the cleanup logic via a simple HTTP server compatible with Vercel's Python runtime. ```python from http.server import BaseHTTPRequestHandler from upstash_redis import Redis redis = Redis(url="https://YOUR_REDIS_URL", token="YOUR_TOKEN") def delete_all_entries(): keys = redis.keys("*") # Match all keys redis.delete(*keys) class handler(BaseHTTPRequestHandler): def do_POST(self): delete_all_entries() self.send_response(200) self.end_headers() ``` -------------------------------- ### Import QStash Receiver Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Import the Receiver class from the QStash SDK. ```ts import { Receiver } from "@upstash/qstash"; ``` -------------------------------- ### Publish to a URL Group via SDKs Source: https://upstash.com/docs/qstash/howto/publishing Demonstrates publishing to a URL group using cURL, TypeScript, and Python. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/my-url-group' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ urlGroup: "my-url-group", body: { "hello": "world" }, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url_group="my-url-group", body={ "hello": "world", }, ); ``` -------------------------------- ### Create a Cron Job API Handler in Next.js Source: https://upstash.com/docs/qstash/recipes/periodic-data-updates Implements a serverless function that fetches Bitcoin prices and stores them in Redis, using verifySignature to ensure requests originate from QStash. ```ts import { NextApiRequest, NextApiResponse } from "next"; import { Redis } from "@upstash/redis"; import { verifySignature } from "@upstash/qstash/nextjs"; /** * You can use any database you want, in this case we use Redis */ const redis = Redis.fromEnv(); /** * Load the current bitcoin price in USD and store it in our database at the * current timestamp */ async function handler(_req: NextApiRequest, res: NextApiResponse) { try { /** * The API returns something like this: * ```json * { * "USD": { * "last": 123 * }, * ... * } * ``` */ const raw = await fetch("https://blockchain.info/ticker"); const prices = await raw.json(); const bitcoinPrice = prices["USD"]["last"] as number; /** * After we have loaded the current bitcoin price, we can store it in the * database together with the current time */ await redis.zadd("bitcoin-prices", { score: Date.now(), member: bitcoinPrice, }); res.send("OK"); } catch (err) { res.status(500).send(err); } finally { res.end(); } } /** * Wrap your handler with `verifySignature` to automatically reject all * requests that are not coming from Upstash. */ export default verifySignature(handler); /** * To verify the authenticity of the incoming request in the `verifySignature` * function, we need access to the raw request body. */ export const config = { api: { bodyParser: false, }, }; ``` -------------------------------- ### Configure QStash Client with Custom Retries (Python) Source: https://upstash.com/docs/qstash/overall/llms-txt Configures the QStash client with a custom retry count and backoff function. ```python from qstash import QStash client = QStash( "", retry={ "retries": 3, "backoff": lambda retry_count: (2**retry_count) * 20, }, ) ``` -------------------------------- ### List All QStash Schedules Source: https://upstash.com/docs/qstash/howto/delete-schedule Retrieves a list of all schedules to find specific schedule IDs. ```shell curl \ -H 'Authorization: Bearer XXX' \ 'https://qstash.upstash.io/v2/schedules' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); ``` ```python from qstash import QStash client = QStash("") client.schedule.list() ``` -------------------------------- ### Create Initial UI Component Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs A basic React component for the home page featuring a button to trigger background jobs. ```tsx "use client" export default function Home() { return (
) } ``` -------------------------------- ### Publish message to local endpoint via QStash Source: https://upstash.com/docs/qstash/howto/local-tunnel Send a POST request to QStash to trigger your local webhook endpoint. ```bash curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://e02f-2a02-810d-af40-5284-b139-58cc-89df-b740.eu.ngrok.io/api/webhooks' ``` -------------------------------- ### Publishing a Background Job Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Initial implementation of a server action to publish a JSON payload to a QStash endpoint. ```typescript "use server" import { Client } from "@upstash/qstash" const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }) export async function startBackgroundJob() { await qstashClient.publishJSON({ // Replace with your public URL url: "https://qstash-bg-job.vercel.app/api/long-task", body: { hello: "world", }, }) } ``` -------------------------------- ### Create Schedule JSON Configuration Source: https://upstash.com/docs/qstash/overall/llms-txt Defines a schedule payload to run every minute. ```json { "destination": "my-url-group", "cron": "* * * * *" } ``` -------------------------------- ### Get a single flow control key Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the current status and configuration of a specific flow control key. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info.flowControlKey); console.log(info.waitListSize); console.log(info.parallelismMax); console.log(info.parallelismCount); console.log(info.rateMax); console.log(info.rateCount); console.log(info.ratePeriod); console.log(info.ratePeriodStart); console.log(info.isPaused); console.log(info.isPinnedParallelism); console.log(info.isPinnedRate); ``` -------------------------------- ### Publishing a Message with Callbacks Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Details on how to configure callback and failure callback headers when publishing a message to QStash. ```APIDOC ## Headers for Message Publishing ### Description Configure message delivery callbacks and failure handling using specific request headers. ### Parameters #### Request Headers - **Upstash-Callback** (string) - Optional - URL to be called after message delivery (success or failure). - **Upstash-Callback-Forward-*** (string) - Optional - Custom headers to forward to the callback URL. - **Upstash-Callback-*** (string) - Optional - Configuration headers for the callback (Method, Timeout, Retries, Retry-Delay). - **Upstash-Failure-Callback** (string) - Optional - URL to be called when message delivery fails after all retries. - **Upstash-Failure-Callback-Forward-*** (string) - Optional - Custom headers to forward to the failure callback URL. - **Upstash-Failure-Callback-*** (string) - Optional - Configuration headers for the failure callback (Method, Timeout, Retries). ``` -------------------------------- ### Implement Database Cleanup Logic Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Python script to connect to Redis and delete all keys. ```python from upstash_redis import Redis redis = Redis(url="https://YOUR_REDIS_URL", token="YOUR_TOKEN") def delete_all_entries(): keys = redis.keys("*") # Match all keys redis.delete(*keys) delete_all_entries() ``` -------------------------------- ### Create a schedule with callbacks Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Configures a schedule to send results or failure notifications to specific callback URLs. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://my-api...", cron="0 * * * *", callback="https://my-callback...", failure_callback="https://my-failure-callback...", ) ``` -------------------------------- ### Pause and resume a queue Source: https://upstash.com/docs/qstash/sdks/py/examples/queues Demonstrates how to pause and resume queue processing. Resuming a queue may take up to a minute. ```python from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.upsert(queue_name, parallelism=1) client.queue.pause(queue_name) queue = client.queue.get(queue_name) print(queue.paused) # prints True client.queue.resume(queue_name) ``` -------------------------------- ### client.queue().upsert() Source: https://upstash.com/docs/qstash/overall/llms-txt Configures the parallelism level for a specific QStash queue using the TypeScript client library. ```APIDOC ## client.queue({ queueName: "my-queue" }).upsert({ parallelism: 1 }) ### Description Configures the parallelism level for a specific QStash queue using the TypeScript client library. ### Method client.queue().upsert() ### Parameters #### queueName (string) - **queueName** (string) - Required - The name of the queue to configure. #### upsert options (object) - **parallelism** (number) - Required - The desired parallelism level for the queue. ### Request Example ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.upsert({ parallelism: 1, }) ``` ### Response #### Success Response - **Success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### GET /messages/{messageId} Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves details of a specific message using its ID. This endpoint is for messages in the process of delivery or retries. ```APIDOC ## GET /messages/{messageId} ### Description Retrieves details of a specific message using its ID. This endpoint is for messages in the process of delivery or retries, as messages are removed shortly after delivery. ### Method GET ### Endpoint /messages/{messageId} ### Parameters #### Path Parameters - **messageId** (string) - Required - The unique identifier of the message. ``` -------------------------------- ### Get Single Flow Control Key Source: https://upstash.com/docs/qstash/overall/llms-txt Represents the JSON structure returned when querying a specific flow control key. ```json { "key": "string", "wait_list_size": 0, "parallelism_max": 0, "parallelism_count": 0, "rate_max": 0, "rate_count": 0, "rate_period": 0, "rate_period_start": 0, "is_paused": false, "is_pinned_parallelism": false, "is_pinned_rate": false } ``` -------------------------------- ### QStash Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule Overview of headers used to control message delivery, retries, and callbacks in QStash. ```APIDOC ## QStash Configuration Headers ### Description These headers are used to configure the behavior of message delivery, including retry logic, scheduling delays, and callback configurations. ### Parameters #### Request Headers - **Upstash-Retries** (integer) - Optional - Number of times to retry a failed delivery. Default is 3. - **Upstash-Retry-Delay** (string) - Optional - Mathematical expression to compute delay between retries. - **Upstash-Delay** (string) - Optional - Delay message delivery. Format: (s, m, h, d). - **Upstash-Forward-*** (string) - Optional - Custom headers to forward to the destination endpoint. - **Upstash-Callback** (string) - Optional - URL to receive a callback after each attempt. - **Upstash-Callback-Forward-*** (string) - Optional - Custom headers to forward to the callback URL. - **Upstash-Callback-Method** (string) - Optional - HTTP method for the callback request. Default is POST. - **Upstash-Callback-Timeout** (string) - Optional - Timeout duration for the callback request. ``` -------------------------------- ### Create Schedule (with Callbacks) Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule with optional callback URLs for handling success and failure notifications. ```APIDOC ## Create Schedule (with Callbacks) ### Description Creates a schedule with optional callback URLs for handling success and failure notifications. ### Method `client.schedules.create(options)` ### Parameters #### Request Body - **destination** (string) - Required - The URL or URL Group to send the request to. - **cron** (string) - Required - The cron expression defining the schedule's frequency. - **callback** (string) - Optional - The URL to send a success notification to. - **failureCallback** (string) - Optional - The URL to send a failure notification to. ``` -------------------------------- ### List URL Groups OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/url-groups/list-url-groups The OpenAPI definition for the GET /v2/topics endpoint used to retrieve all URL groups. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/topics: get: tags: - URL Groups summary: List URL Groups description: List all your URL Groups responses: '200': description: '' content: application/json: schema: type: array items: $ref: '#/components/schemas/URLGroup' components: schemas: URLGroup: type: object properties: name: type: string description: URL Group name createdAt: type: integer description: Creation timestamp of URL Group in Unix milliseconds updatedAt: type: integer description: Last update timestamp of URL Group in Unix milliseconds endpoints: type: array items: $ref: '#/components/schemas/Endpoint' Endpoint: type: object properties: name: type: string description: The name of the endpoint url: type: string description: The URL of the endpoint securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Register QStash Dev Server for Next.js Edge Routes Source: https://upstash.com/docs/qstash/howto/local-development Call registerQStashDev in instrumentation.ts to ensure the dev server is reachable for edge runtime requests. ```typescript // instrumentation.ts import { registerQStashDev } from "@upstash/qstash/nextjs"; export const register = () => registerQStashDev(); ``` -------------------------------- ### client.schedules.list() Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieve a list of all schedules using the QStash TypeScript SDK. ```APIDOC ## client.schedules.list() ### Description Retrieve a list of all schedules using the QStash TypeScript SDK's `schedules.list()` method. ### Method Signature `await client.schedules.list()` ``` -------------------------------- ### Retrieve Message Logs with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Fetch logs for published messages using an initialized QStash client. ```typescript const client = new Client({ token: "" }); const logs = await client.logs() ``` -------------------------------- ### Implement Webhook Handler in Deno Source: https://upstash.com/docs/qstash/quickstarts/deno-deploy Uses the Upstash QStash Receiver to verify incoming webhook signatures using environment-provided signing keys. ```ts import { serve } from "https://deno.land/std@0.142.0/http/server.ts"; import { Receiver } from "https://deno.land/x/upstash_qstash@v0.1.4/mod.ts"; serve(async (req: Request) => { const r = new Receiver({ currentSigningKey: Deno.env.get("QSTASH_CURRENT_SIGNING_KEY")!, nextSigningKey: Deno.env.get("QSTASH_NEXT_SIGNING_KEY")!, }); const isValid = await r .verify({ signature: req.headers.get("Upstash-Signature")!, body: await req.text(), }) .catch((err: Error) => { console.error(err); return false; }); if (!isValid) { return new Response("Invalid signature", { status: 401 }); } console.log("The signature was valid"); // do work return new Response("OK", { status: 200 }); }); ``` -------------------------------- ### Create a basic schedule Source: https://upstash.com/docs/qstash/features/schedules Create a recurring schedule that publishes a message every minute. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "* * * * *", }); ``` ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="* * * * *", ) ``` ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ``` -------------------------------- ### POST /v2/queues Source: https://upstash.com/docs/qstash/api-reference/queues/upsert-a-queue Updates or creates a queue in QStash. ```APIDOC ## POST /v2/queues ### Description Updates or creates a queue. ### Method POST ### Endpoint /v2/queues ### Request Body - **queueName** (string) - Required - The name of the queue - **parallelism** (integer) - Required - The number of parallel consumers consuming from the queue. Must be greater than 0. ### Response #### Success Response (200) - Queue created or updated successfully #### Error Response (400) - Queue name is invalid. Queue names can only contain alphanumeric characters, hyphens, periods, and underscores. #### Error Response (412) - Either exceeded the maximum number of queues allowed or the maximum parallelism per queue. ``` -------------------------------- ### Get Single Flow Control Key API Documentation Source: https://upstash.com/docs/qstash/overall/llms-txt Defines the response schema for retrieving flow control key details. ```APIDOC ## Get Single Flow Control Key (API Doc) ### Description Retrieves detailed information about a specific flow control key, including its current state and configuration limits. This is a GET request to the /v1/flowcontrol/{key} endpoint. ### Response #### Success Response (200) - **key** (string) - The identifier for the flow control key. - **wait_list_size** (integer) - The number of items currently waiting in the queue. - **parallelism_max** (integer) - The maximum allowed concurrent operations. - **parallelism_count** (integer) - The current number of concurrent operations. - **rate_max** (integer) - The maximum number of operations allowed within a given period. - **rate_count** (integer) - The current number of operations performed within the period. - **rate_period** (integer) - The duration of the rate limiting period in seconds. - **rate_period_start** (integer) - The timestamp when the current rate period started. - **is_paused** (boolean) - Indicates if the flow control is currently paused. - **is_pinned_parallelism** (boolean) - Indicates if the parallelism is pinned. - **is_pinned_rate** (boolean) - Indicates if the rate is pinned. ``` -------------------------------- ### GET /v1/flowcontrol/status Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current status of a flow control key, including wait list size and parallelism/rate limiting configurations. ```APIDOC ## GET /v1/flowcontrol/status ### Description Retrieves the current status of a flow control key, including wait list size and parallelism/rate limiting configurations. ### Method GET ### Endpoint /v1/flowcontrol/status ### Parameters #### Query Parameters - **flowControlKey** (string) - Required - The key for which to retrieve flow control status. ### Response #### Success Response (200 OK) - **flowControlKey** (string) - The identifier for the flow control key. - **waitListSize** (integer) - The current number of items waiting in the queue. - **parallelismMax** (integer) - The maximum allowed concurrent requests. - **parallelismCount** (integer) - The current number of active concurrent requests. - **rateMax** (integer) - The maximum number of requests allowed within the rate period. - **rateCount** (integer) - The current number of requests made within the rate period. - **ratePeriod** (integer) - The duration of the rate limiting period in seconds. - **ratePeriodStart** (integer) - The Unix timestamp when the current rate period started. - **isPinnedParallelism** (boolean) - Indicates if parallelism is pinned. - **isPinnedRate** (boolean) - Indicates if rate limiting is pinned. - **isPaused** (boolean) - Indicates if the flow control is currently paused. ### Response Example { "flowControlKey": "my-flow-key", "waitListSize": 10, "parallelismMax": 5, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ``` -------------------------------- ### Retrieve Queue Details with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Fetches details for a specific queue using the QStash Python client. ```python from qstash import QStash client = QStash("") client.queue.get("my-queue") ``` -------------------------------- ### Retrieve Flow Control Key via cURL Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves details for a specific flow control key using a GET request. ```bash curl -X GET https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY \ -H "Authorization: Bearer " ``` -------------------------------- ### Schedule to a URL Group with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule to publish messages to a URL Group using the QStash SDK. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "urlGroupName", cron: "* * * * *", }); ``` -------------------------------- ### OpenAPI Specification for Get Global Parallelism Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-global-parallelism The OpenAPI definition for the /v2/globalParallelism endpoint, including request method, tags, and response schema. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/globalParallelism: get: tags: - Flow Control summary: Get Global Parallelism description: >- Returns the current global parallelism usage across all flow control keys responses: '200': description: Global parallelism info retrieved successfully content: application/json: schema: type: object properties: parallelismMax: type: integer description: The configured maximum global parallelism parallelismCount: type: integer description: >- The current number of messages running globally in parallel components: securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Publishing a Message with a Callback Source: https://upstash.com/docs/qstash/features/callbacks Configure a callback URL when publishing a message to receive status updates. The callback URL must be a valid endpoint reachable by QStash. ```bash curl -X POST \ https://qstash.upstash.io/v2/publish/https://my-api... \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Callback: ' \ -d '{ "hello": "world" }' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, callback: "https://my-callback...", }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, callback="https://my-callback...", ) ``` -------------------------------- ### Update QStash SDK dependency Source: https://upstash.com/docs/qstash/howto/multi-region Use this command to ensure the SDK is at the minimum version required for multi-region support. ```bash npm install @upstash/qstash@latest ``` -------------------------------- ### Create a queue with parallelism Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Initializes a queue with a specific parallelism setting and retrieves its details. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const queueName = "upstash-queue"; await client.queue({ queueName }).upsert({ parallelism: 2 }); const queueDetails = await client.queue({ queueName }).get(); ``` -------------------------------- ### Expose local port with localtunnel Source: https://upstash.com/docs/qstash/howto/local-tunnel Use this command to generate a public URL for a local server running on a specific port. ```bash npx localtunnel --port 3000 ``` -------------------------------- ### Retrieve DLQ Message Details API Specification Source: https://upstash.com/docs/qstash/overall/llms-txt Defines the GET endpoint for fetching specific message details from the Dead Letter Queue. ```APIDOC ## GET /v2/dlq/{dlqId} ### Description Get a specific message from the DLQ. ### Method GET ### Endpoint /v2/dlq/{dlqId} ### Parameters #### Path Parameters - **dlqId** (string) - Required - The DLQ ID of the message you want to retrieve. ### Response #### Success Response (200) - **messageId** (string) - Unique identifier for the message - **url** (string) - The URL to which the message should be delivered. - **topicName** (string) - The URL Group (a.k.a. topic) name if this message was sent to a URL Group. - **endpointName** (string) - The endpoint name of the message if the endpoint is given a name within the URL group. - **method** (string) - The HTTP method to use for the message. - **header** (object) - The HTTP headers sent to your API. - **body** (string) - The body of the message if it is composed of utf8 chars only, empty otherwise. - **bodyBase64** (string) - The base64 encoded body if the body contains a non-utf8 char only, empty otherwise. - **maxRetries** (integer) - The number of retries that should be attempted in case of delivery failure. - **notBefore** (integer) - The unix timestamp in milliseconds before which the message should not be delivered. - **createdAt** (integer) - The unix timestamp in milliseconds when the message was created. - **callback** (string) - The url where we send a callback each time the message is attempted to be delivered. - **failureCallback** (string) - The url where we send a callback to after the message is failed - **queueName** (string) - The name of the queue if the message is enqueued to a queue. - **scheduleId** (string) - The scheduleId of the message if the message is triggered by a schedule - **callerIP** (string) - IP address of the publisher of this message. - **label** (string) - The label of the message assigned by the user. - **flowControlKey** (string) - The flow control key used for rate limiting. - **rate** (integer) - The rate value used for flow control. - **period** (integer) - The period value used for flow control. - **parallelism** (integer) - The parallelism value used for flow control. - **responseStatus** (integer) - The HTTP status code received from the destination API. - **responseHeader** (object) - The HTTP response headers received from the destination API. ``` -------------------------------- ### List Flow Control Keys OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/flow-control/list-flow-control-keys Defines the GET /v2/flowControl endpoint and the FlowControlKey schema for monitoring flow control configurations. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/flowControl: get: tags: - Flow Control summary: List Flow Control Keys description: List all Flow Control keys responses: '200': description: Flow control keys retrieved successfully content: application/json: schema: type: array items: $ref: '#/components/schemas/FlowControlKey' components: schemas: FlowControlKey: type: object properties: flowControlKey: type: string description: The flow control key name waitListSize: type: integer description: The number of messages waiting due to flow control configuration. parallelismMax: type: integer description: >- The configured maximum number of messages allowed to run concurrently, if parallelism is set. parallelismCount: type: integer description: The current number of messages running in parallel. rateMax: type: integer description: >- The configured maximum number of messages allowed per rate period, if rate limiting is set. rateCount: type: integer description: The number of messages dispatched in the current rate period. ratePeriod: type: integer description: The length of the rate period in seconds. ratePeriodStart: type: integer description: Unix timestamp (seconds) when the current rate period started. isPinnedParallelism: type: boolean description: True if the flow-control key has a pinned parallelism configuration. isPinnedRate: type: boolean description: True if the flow-control key has a pinned rate configuration. isPaused: type: boolean description: >- True if the delivery of messages associated with the flow-control key is paused. securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Publish a Chat Completion Request with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Sends a chat completion request to an OpenAI-compatible provider via the QStash Python client. ```python from qstash import QStash from qstash.chat import upstash q = QStash("") result = q.message.publish_json( api={"name": "llm", "provider": openai("")}, body={ "model": "gpt-3.5-turbo", "messages": [ { "role": "user", "content": "Write a hello world program in Rust.", } ], }, callback="https://abc.requestcatcher.com/", ) print(result) ``` -------------------------------- ### Configure Single-Region Mode Source: https://upstash.com/docs/qstash/howto/multi-region Set these environment variables to operate in the default single-region mode. ```bash # Single-region configuration (EU) QSTASH_URL="https://qstash.upstash.io" QSTASH_TOKEN="your_eu_token" QSTASH_CURRENT_SIGNING_KEY="your_eu_current_key" QSTASH_NEXT_SIGNING_KEY="your_eu_next_key" ``` -------------------------------- ### Retrieve Message Logs with Python Source: https://upstash.com/docs/qstash/overall/llms-txt Lists event logs for published messages using the QStash Python SDK. ```python from qstash import QStash client = QStash("") client.event.list() ``` -------------------------------- ### Publish Message to QStash Source: https://upstash.com/docs/qstash/quickstarts/deno-deploy Sends a POST request to the QStash API to trigger the webhook endpoint. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/https://early-frog-33.deno.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Get Message Details via HTTP Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves details of a specific message using its ID. Applicable for messages currently in delivery or retry states. ```http GET /messages/{messageId} ``` -------------------------------- ### Create a Schedule with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule to publish a message periodically using a cron expression. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="* * * * *", ) ``` -------------------------------- ### Get Flow Control Key OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-flow-control-key Defines the endpoint path, parameters, and response schema for retrieving flow control key details. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/flowControl/{flowControlKey}: get: tags: - Flow Control summary: Get Flow Control Key description: Get details of a specific Flow Control key parameters: - name: flowControlKey in: path required: true schema: type: string description: The Flow Control key to retrieve responses: '200': description: Flow control key details content: application/json: schema: $ref: '#/components/schemas/FlowControlKey' '404': description: Flow Control key not found content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: FlowControlKey: type: object properties: flowControlKey: type: string description: The flow control key name waitListSize: type: integer description: The number of messages waiting due to flow control configuration. parallelismMax: type: integer description: >- The configured maximum number of messages allowed to run concurrently, if parallelism is set. parallelismCount: type: integer description: The current number of messages running in parallel. rateMax: type: integer description: >- The configured maximum number of messages allowed per rate period, if rate limiting is set. rateCount: type: integer description: The number of messages dispatched in the current rate period. ratePeriod: type: integer description: The length of the rate period in seconds. ratePeriodStart: type: integer description: Unix timestamp (seconds) when the current rate period started. isPinnedParallelism: type: boolean description: True if the flow-control key has a pinned parallelism configuration. isPinnedRate: type: boolean description: True if the flow-control key has a pinned rate configuration. isPaused: type: boolean description: >- True if the delivery of messages associated with the flow-control key is paused. Error: type: object required: - error properties: error: type: string description: Error message securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Create URL Group and Add Endpoints Source: https://upstash.com/docs/qstash/overall/llms-txt Programmatically create a URL group and add named endpoints using the QStash TypeScript SDK. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.addEndpoints({ name: "urlGroupName", endpoints: [ { name: "endpoint1", url: "https://example.com" }, { name: "endpoint2", url: "https://somewhere-else.com" }, ], }); ``` -------------------------------- ### Initialize QStash Receiver in Cloudflare Workers Source: https://upstash.com/docs/qstash/overall/llms-txt Configures the Receiver by fetching signing keys from Cloudflare environment secrets. ```typescript import { Receiver } from "@upstash/qstash"; export interface Env { QSTASH_CURRENT_SIGNING_KEY: SecretsStoreSecret; QSTASH_NEXT_SIGNING_KEY: SecretsStoreSecret; } export default { async fetch(request, env, ctx): Promise { const c = new Receiver ({ currentSigningKey: await env.QSTASH_CURRENT_SIGNING_KEY.get(), nextSigningKey: await env.QSTASH_NEXT_SIGNING_KEY.get(), }); // Rest of the code }, }; ``` -------------------------------- ### Retrieve Queue Details Source: https://upstash.com/docs/qstash/features/queues Check the current configuration and status of a specific queue. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() ``` ```python from qstash import QStash client = QStash("") client.queue.get("my-queue") ``` -------------------------------- ### Create a URL Group and add endpoints Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Initializes a URL group with a specified name and a list of endpoint URLs. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const urlGroups = client.urlGroups; await urlGroups.addEndpoints({ name: "url_group_name", endpoints: [ { url: "https://my-endpoint-1" }, { url: "https://my-endpoint-2" }, ], }); ``` -------------------------------- ### Configure Retry Policy Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Customize the client retry behavior by passing a configuration dictionary to the constructor. ```python from qstash import QStash client = QStash( "", retry={ "retries": 3, "backoff": lambda retry_count: (2**retry_count) * 20, }, ) ``` -------------------------------- ### Send Chat Completion Requests in Batches (Python) Source: https://upstash.com/docs/qstash/overall/llms-txt Sends multiple chat completion requests concurrently using QStash's batching functionality. ```python from qstash import QStash from qstash.chat import upstash q = QStash("") result = q.message.batch_json( [ { "api":{"name": "llm", "provider": openai("")}, "body": {...}, "callback": "https://abc.requestcatcher.com", }, ... ] ) print(result) ``` -------------------------------- ### POST /v2/schedules/ Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule to add an item to a specified queue at a defined time. ```APIDOC ## POST /v2/schedules/ ### Description Creates a schedule to add an item to a specified queue. ### Method POST ### Endpoint /v2/schedules/ ### Headers - Authorization: Bearer - Content-type: application/json - Upstash-Cron: - Upstash-Queue-Name: ### Request Body - destination (string) - The URL to send the message to. ``` -------------------------------- ### Create a schedule with callbacks Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Configures a schedule to send results to a callback URL and handle failures with a specific failure callback. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://my-api...", cron: "0 * * * *", callback: "https://my-callback...", failureCallback: "https://my-failure-callback...", }); ``` -------------------------------- ### Update UI with Server Action Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs The updated home page component that invokes the startBackgroundJob server action on button click. ```tsx "use client" import { startBackgroundJob } from "@/app/actions" export default function Home() { async function handleClick() { await startBackgroundJob() } return (
) } ``` -------------------------------- ### client.message.batch_json(messages: List[Dict]) Source: https://upstash.com/docs/qstash/overall/llms-txt Sends a batch of messages using the QStash Python client. ```APIDOC ## client.message.batch_json(messages: List[Dict]) ### Description Sends a batch of messages using the QStash Python client. ### Method client.message.batch_json ### Parameters #### messages (List[Dict]) - **List of Message Dictionaries** (list) - Required - Each dictionary represents a message to be sent in the batch. - **url_group** (string) - Required - The URL group to send the message to. - **url** (string) - Required - The URL to send the message to. - **delay** (string) - Optional - Delay for the message (e.g., "5s", "1m"). - **body** (dict) - Optional - The body of the message. - **headers** (dict) - Optional - Custom headers for the message. - **random** (string) - Example of a custom header. ### Request Example ```python client.message.batch_json( [ { "url_group": "my-url-group", "delay": "5s", "body": {"hello": "world"}, "headers": {"random": "header"}, }, { "url": "https://example.com/destination1", "delay": "1m", }, { "url": "https://example.com/destination2", "body": {"hello": "again"}, }, ] ) ``` ### Response #### Success Response - **List of Results** (list) - A list where each element corresponds to a message in the batch request. - **messageId** (string) - The ID of the sent message. - **url** (string) - The URL the message was sent to (if applicable). #### Response Example ```json [ [ { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint1.com" }, { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint2.com" } ], { "messageId": "msg_..." }, { "messageId": "msg_..." } ] ``` ``` -------------------------------- ### Test AWS Lambda Integration via CURL Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Use this command to send a POST request to your Lambda function URL through QStash for integration verification. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Publish a message using cURL Source: https://upstash.com/docs/qstash/overall/getstarted Use these commands to send a JSON payload to a specified API endpoint via the QStash publish API. ```bash curl -XPOST \ -H 'Authorization: Bearer ' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://' ``` ```bash curl -XPOST \ -H 'Authorization: Bearer ' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://firstqstashmessage.requestcatcher.com/test' ``` -------------------------------- ### Handling Burst Rate Limit Error Source: https://upstash.com/docs/qstash/api/api-ratelimiting Demonstrates how to catch and handle the QstashRatelimitError when a burst rate limit (per second) is exceeded. ```APIDOC import { QstashRatelimitError } from "@upstash/qstash"; try { const result = await client.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); } catch (error) { if (error instanceof QstashRatelimitError) { console.log("Burst rate limit exceeded. Retry after:", error.reset); } else { console.error("An unexpected error occurred:", error); } } ``` -------------------------------- ### Scaffold Cloudflare Worker project Source: https://upstash.com/docs/qstash/overall/llms-txt Command to initialize a new Cloudflare Worker project using npm. ```shell npm create cloudflare@latest ``` -------------------------------- ### Publish a background job with TypeScript Source: https://upstash.com/docs/qstash/overall/usecases Use the QStash client to publish a JSON payload to an endpoint for asynchronous processing with automatic retries. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: process.env.QSTASH_TOKEN! }); await client.publishJSON({ url: "https://your-app.com/api/process-video", body: { videoId }, retries: 3, }); ``` -------------------------------- ### Configure Queue Parallelism with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Upserts queue configuration to set parallelism using the QStash client. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.upsert({ parallelism: 1, }) ``` -------------------------------- ### POST /v2/enqueue/{queueName}/{destination} Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Enqueue a message to the specified queue. If the queue does not exist, it will be created automatically. ```APIDOC ## POST /v2/enqueue/{queueName}/{destination} ### Description Enqueue a message to the specified queue. If the queue does not exist, it will be created automatically with default parallelism. ### Method POST ### Endpoint /v2/enqueue/{queueName}/{destination} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue that message will be enqueued on. - **destination** (string) - Required - Destination can either be a valid URL or a URL Group name. #### Header Parameters - **Content-Type** (string) - Optional - The MIME type of the message (e.g., application/json). - **Upstash-Forward-*** (string) - Optional - Custom headers to be forwarded to the destination, prefixed with Upstash-Forward-. - **Upstash-Method** (string) - Optional - The HTTP method to use when sending the request to your API (GET, POST, PUT, PATCH, DELETE). - **Upstash-Timeout** (string) - Optional - Specifies the maximum duration the request is allowed to take before timing out. ``` -------------------------------- ### Message Publishing Headers Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Configuration headers for controlling message delivery behavior in QStash. ```APIDOC ## Message Publishing Headers ### Description These headers can be used when publishing a message to configure retry logic, delivery delays, deduplication, and flow control. ### Parameters #### Request Headers - **Upstash-Retries** (integer) - Optional - Number of times to retry delivery. Default is 3. - **Upstash-Retry-Delay** (string) - Optional - Mathematical expression to compute delay between retries. - **Upstash-Delay** (string) - Optional - Delay message delivery. Format: (s, m, h, d). - **Upstash-Not-Before** (integer) - Optional - Unix timestamp (seconds) to delay delivery until. - **Upstash-Label** (string) - Optional - Comma-separated labels for identification. - **Upstash-Flow-Control-Key** (string) - Optional - Key for rate limiting. - **Upstash-Flow-Control-Value** (string) - Optional - Rate limit configuration (parallelism, rate, period). - **Upstash-Deduplication-Id** (string) - Optional - ID to prevent duplicate messages within 10 minutes. - **Upstash-Content-Based-Deduplication** (string) - Optional - Enable content-based deduplication (true/false). ``` -------------------------------- ### Batch Publish to Destinations (TypeScript) Source: https://upstash.com/docs/qstash/overall/llms-txt Uses the QStash client to send multiple messages to different destinations in a single batch request. ```typescript import { Client } from "@upstash/qstash"; // Each message is the same as the one you would send with the publish endpoint const client = new Client({ token: "" }); const res = await client.batchJSON([ { url: "https://example.com/destination1", }, { url: "https://example.com/destination2", }, ]); ``` -------------------------------- ### QStash Schedule Response JSON Source: https://upstash.com/docs/qstash/overall/llms-txt Represents a successful response when querying for schedules, including cron, destination, and timing details. ```json [ { "scheduleId": "sch_abc123", "cron": "* * * * *", "destination": "https://example.com/webhook", "createdAt": 1678886400000, "method": "POST", "header": { "Content-Type": ["application/json"] }, "body": "{\"message\": \"Hello, world!\"}", "retries": 3, "delay": 60, "callback": "https://example.com/callback", "failureCallback": "https://example.com/failure", "callerIp": "192.168.1.1", "isPaused": false, "flowControlKey": "fc_key_123", "parallelism": 10, "rate": 100, "period": 60, "retryDelayExpression": "1m * pow(2, attempt)", "label": "my-schedule", "lastScheduleTime": 1678886400000, "nextScheduleTime": 1678886460000, "lastScheduleStates": { "status": "success" } } ] ``` -------------------------------- ### Publish a message with 5 minutes delay Source: https://upstash.com/docs/qstash/overall/apiexamples Schedule a message delivery with a specified delay after receipt. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Delay: 5m" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' ``` ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, delay: 300, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, delay="5m", ); # Async version is also available ``` -------------------------------- ### Publish Chat Completion Request (JavaScript) Source: https://upstash.com/docs/qstash/overall/llms-txt Sends a chat completion request to an OpenAI-compatible provider. Requires the @upstash/qstash library. ```javascript import { Client, upstash } from "@upstash/qstash"; const client = new Client({ token: "", }); const result = await client.publishJSON({ api: { name: "llm", provider: openai({ token: "_OPEN_AI_TOKEN_"}) }, body: { model: "gpt-3.5-turbo", messages: [ { role: "user", content: "Write a hello world program in Rust.", }, ], }, callback: "https://abc.requestcatcher.com/", }); console.log(result); ``` -------------------------------- ### List all schedules Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Fetches a list of all schedules associated with the client. ```python from qstash import QStash client = QStash("") all_schedules = client.schedule.list() print(all_schedules) ``` -------------------------------- ### POST /v2/batch Source: https://upstash.com/docs/qstash/features/batch Sends a batch of messages to QStash. Each message in the array can target a URL, a URL group, or a specific queue. ```APIDOC ## POST /v2/batch ### Description Sends multiple messages to QStash in a single request. This is useful for high-throughput scenarios where you need to trigger multiple destinations or queue tasks simultaneously. ### Method POST ### Endpoint https://qstash.upstash.io/v2/batch ### Request Body - **Array** (object) - Required - A list of message objects. Each object can contain: - **destination** (string) - Optional - The URL or URL group name. - **queue** (string) - Optional - The name of the queue to send the message to. - **url** (string) - Optional - The destination URL. ### Request Example [ { "destination": "myUrlGroup" }, { "queue": "my-queue", "destination": "https://example.com/destination1" } ] ``` -------------------------------- ### List all schedules Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve a list of all configured message schedules. ```shell curl https://qstash.upstash.io/v2/schedules \ -H "Authorization: Bearer XXX" ``` ```typescript const client = new Client({ token: "" }); const scheds = await client.schedules.list(); ``` ```python from qstash import QStash client = QStash("") client.schedule.list() # Async version is also available ``` -------------------------------- ### POST /v2/keys/rotate Source: https://upstash.com/docs/qstash/api-reference/signing-keys/rotate-signing-keys Rotates the current signing keys for your QStash account. ```APIDOC ## POST /v2/keys/rotate ### Description Rotate your signing keys. ### Method POST ### Endpoint /v2/keys/rotate ### Response #### Success Response (200) - **current** (string) - The current signing key. - **next** (string) - The next signing key. ``` -------------------------------- ### Publish Background Job with Error Handling Source: https://upstash.com/docs/qstash/overall/llms-txt Publish a JSON message to QStash within a Next.js server action, including error handling. ```typescript "use server" import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }); export async function startBackgroundJob() { try { const response = await qstashClient.publishJSON({ "url": "https://qstash-bg-job.vercel.app/api/long-task", body: { "hello": "world" } }); return response.messageId; } catch (error) { console.error(error); return null; } } ``` ```ts "use server" import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }); export async function startBackgroundJob() { try { const response = await qstashClient.publishJSON({ "url": "https://qstash-bg-job.vercel.app/api/long-task", body: { "hello": "world" } }); return response.messageId; } catch (error) { console.error(error); return null; } } ``` -------------------------------- ### client.schedules.list Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Lists all schedules associated with the client. ```APIDOC ## client.schedules.list ### Description Returns an array of all schedules configured for the account. ``` -------------------------------- ### Create a schedule with labels Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Attaches one or more labels to a schedule for easier filtering in logs. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // attach a single label await client.schedules.create({ destination: "https://my-api...", cron: "* * * * *", label: "my-label", }); // attach multiple labels to the same schedule await client.schedules.create({ destination: "https://my-api...", cron: "* * * * *", label: ["team-a", "high-priority"], }); ``` -------------------------------- ### client.schedules.create Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Creates a new schedule with a specified cron expression and destination. ```APIDOC ## client.schedules.create ### Description Creates a new schedule to trigger a destination URL or URL group based on a cron expression. ### Parameters - **destination** (string) - Required - The URL or URL group to trigger. - **cron** (string) - Required - The cron expression for the schedule. - **callback** (string) - Optional - URL to call upon success. - **failureCallback** (string) - Optional - URL to call upon failure. - **scheduleId** (string) - Optional - A custom identifier for the schedule. - **timeout** (string) - Optional - Timeout in seconds for the request. - **label** (string|string[]) - Optional - Labels to tag the schedule. ``` -------------------------------- ### Pause and resume a schedule Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Demonstrates how to toggle the active state of a schedule. ```python from qstash import QStash client = QStash("") schedule_id = "scd_1234" client.schedule.pause(schedule_id) schedule = client.schedule.get(schedule_id) print(schedule.paused) # prints True client.schedule.resume(schedule_id) ``` -------------------------------- ### POST /v2/schedules/{url} Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule for recurring message execution. ```APIDOC ## POST /v2/schedules/{url} ### Description Creates a schedule for recurring message execution. ### Method POST ### Endpoint /v2/schedules/{url} ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Upstash-Cron** (string) - Required - Cron expression defining the schedule (e.g., "0 * * * *"). - **Content-type** (string) - Required - Specifies the content type, typically application/json. ### Request Body - **destination** (string) - Required - The URL to send messages to. - **cron** (string) - Required - Cron expression for scheduling. - **callback** (string) - Optional - URL to call on success. - **failureCallback** (string) - Optional - URL to call on failure. ### Request Example ```json { "destination": "https://my-api...", "cron": "0 * * * *", "callback": "https://my-callback...", "failureCallback": "https://my-failure-callback..." } ``` ### Response #### Success Response (200) Schedule created successfully. ``` -------------------------------- ### POST /api/send-email Source: https://upstash.com/docs/qstash/overall/llms-txt This API route, when integrated into a Next.js application, uses the QStash client to publish a background job to a specified email API endpoint. ```APIDOC ## POST /api/send-email ### Description This API route, when integrated into a Next.js application, uses the QStash client to publish a background job to a specified email API endpoint. ### Method POST ### Endpoint /api/send-email ### Request Body - **users** (string[]) - Required - A list of user identifiers to send emails to. ### Request Example { "users": ["user1@example.com", "user2@example.com"] } ### Response #### Success Response (200) - **message** (string) - Indicates that the job has been started. ``` -------------------------------- ### Create Periodic Data Fetching API Route with Redis (Next.js) Source: https://upstash.com/docs/qstash/overall/llms-txt Implements a secure Next.js API route using verifySignature to fetch external data and store it in Redis. Requires bodyParser to be disabled for signature verification. ```typescript import { NextApiRequest, NextApiResponse } from "next"; import { Redis } from "@upstash/redis"; import { verifySignature } from "@upstash/qstash/nextjs"; /** * You can use any database you want, in this case we use Redis */ const redis = Redis.fromEnv(); /** * Load the current bitcoin price in USD and store it in our database at the * current timestamp */ async function handler (_req: NextApiRequest, res: NextApiResponse) { try { /** * The API returns something like this: * ```json * { * "USD": { * "last": 123 * }, * ... * } * ``` */ const raw = await fetch("https://blockchain.info/ticker"); const prices = await raw.json(); const bitcoinPrice = prices["USD"]["last"] as number; /** * After we have loaded the current bitcoin price, we can store it in the * database together with the current time */ await redis.zadd("bitcoin-prices", { score: Date.now(), member: bitcoinPrice, }); res.send("OK"); } catch (err) { res.status(500).send(err); } finally { res.end(); } } /** * Wrap your handler with `verifySignature` to automatically reject all * requests that are not coming from Upstash. */ export default verifySignature(handler); /** * To verify the authenticity of the incoming request in the `verifySignature` * function, we need access to the raw request body. */ export const config = { api: { bodyParser: false, }, }; ``` -------------------------------- ### Build and Zip Script for AWS Lambda Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Add this script to your package.json to bundle your code with esbuild and create a zip file ready for AWS Lambda deployment. ```json { "scripts": { "build": "rm -rf ./dist; esbuild index.ts --bundle --minify --sourcemap --platform=node --target=es2020 --outfile=dist/index.js && cd dist && zip -r index.zip index.js*" } } ``` -------------------------------- ### Create a schedule for a URL Group Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Targets a predefined URL group instead of a single destination URL. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "my-url-group", cron: "* * * * *", }); ``` -------------------------------- ### client.dlq.list(cursor=None) Source: https://upstash.com/docs/qstash/sdks/py/examples/dlq Retrieves a paginated list of messages from the DLQ. Use the cursor to iterate through all available messages. ```APIDOC ## client.dlq.list(cursor=None) ### Description Fetches a page of messages from the DLQ. Returns an object containing a list of messages and a cursor for pagination. ### Parameters - **cursor** (string) - Optional - The cursor value to fetch the next page of results. ### Example ```python res = client.dlq.list(cursor=cursor) all_messages.extend(res.messages) cursor = res.cursor ``` ``` -------------------------------- ### Forwarding Headers to Callbacks Source: https://upstash.com/docs/qstash/features/callbacks Syntax for forwarding custom headers to callback endpoints. ```text Upstash-Callback-Forward-MyCustomHeader Upstash-Failure-Callback-Forward-MyCustomHeader ``` -------------------------------- ### client.batchJSON(msgs: Array) Source: https://upstash.com/docs/qstash/overall/llms-txt Sends a batch of messages using the QStash TypeScript client. ```APIDOC ## client.batchJSON(msgs: Array) ### Description Sends a batch of messages using the QStash TypeScript client. ### Method client.batchJSON ### Parameters #### msgs (Array) - **Array of Message Objects** (object[]) - Required - Each object represents a message to be sent in the batch. - **urlGroup** (string) - Required - The URL group to send the message to. - **url** (string) - Required - The URL to send the message to. - **delay** (number) - Optional - Delay in seconds for the message. - **body** (string | object) - Optional - The body of the message. - **headers** (object) - Optional - Custom headers for the message. ### Request Example ```typescript const msgs = [ { urlGroup: "myUrlGroup", delay: 5, body: "Hello World", headers: { hello: "123456", }, }, { url: "https://example.com/destination1", delay: 7, headers: { hello: "789", }, }, { url: "https://example.com/destination2", delay: 9, headers: { hello: "again", }, body: { Some: "Data", }, }, ]; const res = await client.batchJSON(msgs); ``` ``` -------------------------------- ### Define Server Action for QStash Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs A Next.js server action that uses the QStash client to publish a JSON payload to an external endpoint. ```ts "use server" import { Client } from "@upstash/qstash" const qstashClient = new Client({ // Add your token to a .env file token: process.env.QSTASH_TOKEN!, }) export async function startBackgroundJob() { await qstashClient.publishJSON({ url: "https://firstqstashmessage.requestcatcher.com/test", body: { hello: "world", }, }) } ``` -------------------------------- ### Configure Flow Control with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Combines rate limiting, parallelism, and period settings for granular delivery control. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", rate: 10, parallelism: 20, period: "1m" }, }); ``` -------------------------------- ### Create a Schedule Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a new schedule that triggers a destination URL based on a cron expression. ```APIDOC ## client.schedules.create ### Description Creates a new schedule that triggers a destination URL at a specified interval. ### Parameters - **destination** (string) - Required - The URL to trigger. - **cron** (string) - Required - The cron expression for the schedule interval. ``` -------------------------------- ### POST /v2/batch Source: https://upstash.com/docs/qstash/features/batch Sends a batch of messages to QStash. Each message in the array can specify a destination (url or urlGroup), delay, headers, and body. ```APIDOC ## POST /v2/batch ### Description Sends a batch of messages to QStash. Each message in the batch is processed independently. ### Method POST ### Endpoint https://qstash.upstash.io/v2/batch ### Request Body - **Array** (object) - Required - A list of message objects, each containing destination (url or urlGroup), headers, and body. ### Request Example [ { "destination": "myUrlGroup", "headers": { "Upstash-Delay": "5s", "Upstash-Forward-Hello": "123456" }, "body": "Hello World" }, { "destination": "https://example.com/destination1", "headers": { "Upstash-Delay": "7s", "Upstash-Forward-Hello": "789" } } ] ### Response #### Success Response (200) - **Array** (object) - An array containing the result for each message, typically including a messageId and the destination URL. #### Response Example [ { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint1.com" }, { "messageId": "msg_..." } ] ``` -------------------------------- ### client.urlGroups.addEndpoints() Source: https://upstash.com/docs/qstash/overall/llms-txt Create a new URL group and add initial endpoints. ```APIDOC ## client.urlGroups.addEndpoints() ### Description Use this to create a new URL group and add initial endpoints. ### Method Signature `await client.urlGroups.addEndpoints({ name: string, endpoints: Array<{ name?: string, url: string }> })` ``` -------------------------------- ### Configure Retry Policy Source: https://upstash.com/docs/qstash/sdks/ts/gettingstarted Customize the retry behavior for requests sent to QStash by passing a retry configuration object to the constructor. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "", retry: { retries: 3, backoff: retry_count => 2 ** retry_count * 20, }, }); ``` -------------------------------- ### Send a single email with Resend Source: https://upstash.com/docs/qstash/integrations/resend Use the publishJSON method with the resend provider to send a single email. Requires QSTASH_TOKEN and RESEND_TOKEN for authentication. ```typescript import { Client, resend } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.publishJSON({ api: { name: "email", provider: resend({ token: "" }), }, body: { from: "Acme ", to: ["delivered@resend.dev"], subject: "Hello World", html: "

It works!

", }, }); ``` -------------------------------- ### Define Environment Variables Interface Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Update the Env interface to include QStash signing keys. ```ts export interface Env { QSTASH_CURRENT_SIGNING_KEY: string; QSTASH_NEXT_SIGNING_KEY: string; } ``` -------------------------------- ### Callback Configuration Headers Source: https://upstash.com/docs/qstash/features/callbacks HTTP headers used to configure specific behaviors for callback and failure callback requests. ```text Upstash-Callback-Timeout Upstash-Callback-Retries Upstash-Callback-Delay Upstash-Callback-Method Upstash-Failure-Callback-Timeout Upstash-Failure-Callback-Retries Upstash-Failure-Callback-Delay Upstash-Failure-Callback-Method ``` -------------------------------- ### POST /v2/schedules/ Source: https://upstash.com/docs/qstash/overall/llms-txt Creates or overwrites an existing schedule by specifying the scheduleId. If the scheduleId is not provided, a new schedule will be created. ```APIDOC ## POST /v2/schedules/ ### Description Creates or overwrites an existing schedule by specifying the `scheduleId`. ### Method POST ### Endpoint `/v2/schedules/` ### Headers - `Authorization` (string) - Required - Bearer - `Content-type` (string) - Required - application/json - `Upstash-Cron` (string) - Required - - `Upstash-Schedule-Id` (string) - Optional - ### Request Body - `destination` (string) - Required - The URL to send the message to. - `scheduleId` (string) - Optional - The ID of the existing schedule to overwrite. ``` -------------------------------- ### Authenticate with Bearer Token Source: https://upstash.com/docs/qstash/api/authentication Use the Authorization header to include your QSTASH_TOKEN in API requests. ```bash curl https://qstash.upstash.io/v2/publish/... \ -H "Authorization: Bearer " ``` -------------------------------- ### Scaffold Cloudflare Worker project Source: https://upstash.com/docs/qstash/overall/llms-txt Initializes a new Cloudflare Worker project using the yarn package manager. ```shell yarn create cloudflare@latest ``` -------------------------------- ### Handle Daily Rate Limit Error in TypeScript Source: https://upstash.com/docs/qstash/api/api-ratelimiting Catch and handle daily rate limit errors when publishing messages to QStash. ```typescript import { QstashDailyRatelimitError } from "@upstash/qstash"; try { // Example of a publish request that could hit the daily rate limit const result = await client.publishJSON({ url: "https://my-api...", // or urlGroup: "the name or id of a url group" body: { hello: "world", }, }); } catch (error) { if (error instanceof QstashDailyRatelimitError) { console.log("Daily rate limit exceeded. Retry after:", error.reset); // Implement retry logic or notify the user } else { console.error("An unexpected error occurred:", error); } } ``` -------------------------------- ### POST /v2/enqueue/{queueName}/{destination} Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a message to a specified queue, ensuring it's processed in FIFO order. ```APIDOC ## POST /v2/enqueue/{queueName}/{destination} ### Description Publishes a message to a specified queue, ensuring it's processed in FIFO order. ### Method POST ### Endpoint /v2/enqueue// ### Headers - Authorization: Bearer - Content-type: application/json ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the FIFO queue. - **destination** (string) - Required - The URL to send the message to. ### Request Body - (JSON payload of the message to be enqueued) ``` -------------------------------- ### Publish a QStash message in Next.js Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Use the QStash client to publish a JSON payload to a specified URL endpoint after performing local operations. ```tsx import { Client } from "@upstash/qstash" import { NextResponse } from "next/server" const client = new Client({ token: process.env.QSTASH_TOKEN! }) export const POST = async (req: Request) => { // Image uploading logic // 👇 Once uploading is done, queue an image processing task const result = await client.publishJSON({ url: "https://your-api-endpoint.com/process-image", body: { imageId: "123" }, }) return NextResponse.json({ message: "Image queued for processing!", qstashMessageId: result.messageId, }) } ``` -------------------------------- ### client.flowControl.pin(key, config) Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Pins parallelism and rate configurations so they cannot be overridden by incoming messages. ```APIDOC ## client.flowControl.pin(key, config) ### Description Pins parallelism and rate configurations for a specific key to prevent overrides. ### Parameters - **key** (string) - Required - The unique identifier for the flow control key. - **config** (object) - Required - Configuration object containing parallelism, rate, and period (in seconds). ``` -------------------------------- ### Global Parallelism Settings JSON Source: https://upstash.com/docs/qstash/overall/llms-txt Represents the current global parallelism settings including maximum allowed and current count. ```json { "parallelism_max": 100, "parallelism_count": 5 } ``` -------------------------------- ### Schedule a daily task Source: https://upstash.com/docs/qstash/overall/apiexamples Create a recurring schedule using a cron expression. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Upstash-Cron: 0 0 * * *" \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ``` ```typescript const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "0 0 * * *", }); ``` ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="0 0 * * *", ) # Async version is also available ``` -------------------------------- ### POST /v2/topics/:urlGroupName/endpoints Source: https://upstash.com/docs/qstash/overall/llms-txt Create a URL group and add multiple endpoints to it using the QStash REST API. ```APIDOC ## POST /v2/topics/:urlGroupName/endpoints ### Description Use this endpoint to create a URL group and add multiple endpoints to it. ### Method POST ### Endpoint https://qstash.upstash.io/v2/topics/:urlGroupName/endpoints ### Parameters #### Path Parameters - **urlGroupName** (string) - Required - The name of the URL group to create or update. #### Request Body - **endpoints** (array) - Required - A list of endpoint objects containing 'name' and 'url'. ``` -------------------------------- ### OpenAPI Specification for Pinning Flow Control Configuration Source: https://upstash.com/docs/qstash/api-reference/flow-control/pin-configuration-for-flow-control-key Defines the POST endpoint for pinning flow control configurations, including required path parameters and optional query parameters for parallelism, rate, and period. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/flowControl/{flowControlKey}/pin: post: tags: - Flow Control summary: Pin Configuration for Flow Control Key description: Pins a processing configuration for a specific flow-control key. parameters: - name: flowControlKey in: path required: true schema: type: string description: The flow-control key for which the configuration will be pinned. - name: parallelism in: query schema: type: integer description: The parallelism value to apply to the flow-control key. - name: rate in: query schema: type: integer description: The rate value to apply to the flow-control key. - name: period in: query schema: type: integer description: The period value to apply to the flow-control key, in seconds. responses: '200': description: The flow-control key configuration has been pinned. '400': description: >- Bad request. Returned when the flow-control key is not provided, or when the parallelism, rate or period values are invalid. content: application/json: schema: $ref: '#/components/schemas/Error' components: schemas: Error: type: object required: - error properties: error: type: string description: Error message securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT description: QStash authentication token bearerAuthQuery: type: apiKey in: query name: qstash_token description: QStash authentication token passed as a query parameter ``` -------------------------------- ### Create a schedule to a URL group Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Targets a pre-defined URL group for the scheduled task. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="my-url-group", cron="0 * * * *", ) ``` -------------------------------- ### Publish to a URL Group Source: https://upstash.com/docs/qstash/howto/publishing Shows how to target a URL group instead of a single URL for message distribution. ```text https://qstash.upstash.io/v2/publish/https://example.com https://qstash.upstash.io/v2/publish/my-url-group ``` -------------------------------- ### Create a Schedule OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule The OpenAPI definition for the POST /v2/schedules/{destination} endpoint, including parameter definitions for cron expressions, custom IDs, and HTTP method configuration. ```yaml openapi: 3.1.0 info: title: QStash REST API description: | QStash is a message queue and scheduler built on top of Upstash Redis. version: 2.0.0 contact: name: Upstash url: https://upstash.com servers: - url: https://qstash-{region}.upstash.io description: Regional variables: region: default: eu-central-1 enum: - us-east-1 - eu-central-1 security: - bearerAuth: [] - bearerAuthQuery: [] tags: - name: Messages description: Publish and manage messages - name: Queues description: Manage message queues - name: Schedules description: Create and manage scheduled messages - name: URL Groups description: Manage URL groups and endpoints - name: DLQ description: Dead Letter Queue operations - name: Logs description: Log operations - name: Signing Keys description: Manage signing keys - name: Flow Control description: Monitor flow control keys paths: /v2/schedules/{destination}: post: tags: - Schedules summary: Create a Schedule description: Create a schedule to send messages periodically parameters: - name: destination in: path required: true schema: type: string description: > Destination can either be a valid URL where the message gets sent to, or a URL Group name. - If the destination is a URL, make sure the URL is prefixed with a valid protocol (http:// or https://) - If the destination is a URL Group, a new message will be created for each endpoint in the group. - name: Upstash-Cron in: header required: true schema: type: string examples: - '*/5 * * * *' - CRON_TZ=America/New_York */5 * * * * description: > Cron expression defining the schedule frequency. QStash republishes this message whenever the cron expression triggers. Timezones are supported and can be specified with the cron expression. The maximum schedule resolution is 1 minute. - name: Upstash-Schedule-Id in: header schema: type: string description: > Assign a custom schedule ID to the created schedule. This header allows you to set the schedule ID yourself instead of QStash assigning a random ID. If a schedule with the provided ID exists, the settings of the existing schedule will be updated with the new settings. - name: Content-Type in: header schema: type: string description: > `Content-Type` is the MIME type of the message. We highly recommend sending a `Content-Type` header along, as this will help your destination API to understand the content of the message. Set this to whatever data you are sending through QStash, if your message is json, then use `application/json`. Some frameworks like Next.js will not parse your body correctly if the content type is not correct. Examples: - `application/json` - `application/xml` - `application/octet-stream` - `text/plain` - name: Upstash-Method in: header schema: type: string enum: - GET - POST - PUT - PATCH - DELETE default: POST description: The HTTP method to use when sending the request to your API. - name: Upstash-Timeout in: header schema: type: string examples: - 5s - 2m - 1h description: > Specifies the maximum duration the request is allowed to take before timing out. This parameter can be used to shorten the default allowed timeout value on your plan. See Max HTTP Connection Timeout on the pricing page for default values. The format of this header is `` where value is a number and unit is one of: - `s` for seconds - `m` for minutes ``` -------------------------------- ### List all DLQ messages with pagination Source: https://upstash.com/docs/qstash/sdks/py/examples/dlq Iterates through all messages in the DLQ using a cursor to handle pagination. ```python from qstash import QStash client = QStash("") all_messages = [] cursor = None while True: res = client.dlq.list(cursor=cursor) all_messages.extend(res.messages) cursor = res.cursor if cursor is None: break ``` -------------------------------- ### Message Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Details on how to configure callbacks, failure callbacks, and field redaction using custom request headers. ```APIDOC ## Message Configuration Headers ### Description Configure message delivery behavior, including success callbacks, failure handling, and sensitive data redaction, by passing specific headers with your request. ### Callback Configuration Headers - **Upstash-Callback-Method** (string) - Optional - HTTP method for the callback request (Default: POST). - **Upstash-Callback-Timeout** (string) - Optional - Timeout duration for the callback request. - **Upstash-Callback-Retries** (string) - Optional - Number of retries for the callback request. - **Upstash-Callback-Retry-Delay** (string) - Optional - Retry delay for the callback request. ### Failure Callback Headers - **Upstash-Failure-Callback** (string) - Optional - URL to be called when all delivery retries are exhausted. - **Upstash-Failure-Callback-Method** (string) - Optional - HTTP method for the failure callback request (Default: POST). - **Upstash-Failure-Callback-Timeout** (string) - Optional - Timeout duration for the failure callback. - **Upstash-Failure-Callback-Retries** (string) - Optional - Number of retries for the failure callback. - **Upstash-Failure-Callback-Retry-Delay** (string) - Optional - Retry delay for the failure callback. ### Redaction Headers - **Upstash-Redact-Fields** (string) - Optional - Comma-separated list of fields to redact (e.g., 'body', 'headers', 'header[Authorization]'). Redacted fields appear as 'REDACTED:' in logs. ``` -------------------------------- ### Create a scheduled task with a specific timezone Source: https://upstash.com/docs/qstash/features/schedules Configures a schedule to run at 04:00 AM in the America/New_York timezone. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "CRON_TZ=America/New_York 0 4 * * *", }); ``` ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://example.com", cron="CRON_TZ=America/New_York 0 4 * * *", ) ``` ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: CRON_TZ=America/New_York 0 4 * * *" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ``` -------------------------------- ### client.flow_control.pin(key, config) Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Pins parallelism and rate configurations so they cannot be overridden by incoming messages. ```APIDOC ## client.flow_control.pin(key, config) ### Description Locks the parallelism and rate settings for a specific key to prevent modification by incoming messages. ### Parameters - **key** (string) - Required - The unique identifier for the flow control key. - **config** (object) - Required - Configuration object containing 'parallelism', 'rate', and 'period'. ``` -------------------------------- ### Fetch all logs with pagination Source: https://upstash.com/docs/qstash/sdks/ts/examples/logs Iterate through all available logs using a cursor to handle pagination. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const logs = []; let cursor = null; while (true) { const res = await client.logs({ cursor }); logs.push(...res.logs); cursor = res.cursor; if (!cursor) { break; } } ``` -------------------------------- ### Create a schedule with timeout Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Sets a specific timeout duration for the scheduled request. ```python from qstash import QStash client = QStash("") schedule_id = client.schedule.create( destination="https://my-api...", cron="*/5 * * * *", timeout="30s", ) print(schedule_id) ``` -------------------------------- ### Create a Schedule Source: https://upstash.com/docs/qstash/overall/llms-txt Creates a schedule to publish a message at a defined interval using cron expressions. ```APIDOC ## Create a Schedule ### Description Creates a schedule to publish a message at a defined interval using cron expressions. ### Method POST ### Endpoint /v2/schedules/ ### Headers - Authorization: Bearer - Content-type: application/json - Upstash-Cron: ### Request Body - destination (string) - The URL or URL Group to send the message to. ``` -------------------------------- ### client.flowControl.get Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the current status and configuration metrics for a specific flow control key using the Upstash QStash TypeScript SDK. ```APIDOC ## client.flowControl.get ### Description Retrieves the current status and configuration metrics for a specific flow control key using the Upstash QStash TypeScript SDK. ### Method client.flowControl.get ### Parameters - **USER_GIVEN_KEY** (string) - Required - The flow control key to retrieve status for. ### Response #### Success Response (200) - **flowControlKey** (string) - The flow control key. - **waitListSize** (number) - The current size of the wait list. - **parallelismMax** (number) - The maximum allowed parallelism. - **parallelismCount** (number) - The current parallelism count. - **rateMax** (number) - The maximum rate. - **rateCount** (number) - The current rate count. - **ratePeriod** (number) - The rate period in seconds. - **ratePeriodStart** (number) - The start timestamp of the current rate period. - **isPaused** (boolean) - Indicates if the flow control is paused. - **isPinnedParallelism** (boolean) - Indicates if parallelism is pinned. - **isPinnedRate** (boolean) - Indicates if the rate is pinned. ``` -------------------------------- ### qstashClient.publishJSON Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a JSON message to QStash with error handling. Returns the message ID on success or null on failure. ```APIDOC ## qstashClient.publishJSON ### Description Publishes a JSON message to QStash with error handling. Returns the message ID on success or null on failure. ### Method `qstashClient.publishJSON` ### Parameters - **url** (string) - Required - The URL to send the message to. - **body** (object) - Required - The JSON body of the message. ``` -------------------------------- ### Set Callback URLs with Python SDK Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a JSON message with specified success and failure callback endpoints. ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, callback="https://example.com/callback", failure_callback="https://example.com/failure", ) # Async version is also available ``` -------------------------------- ### List all URL Groups Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Fetches a list of all existing URL groups. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allUrlGroups = await client.urlGroups.list(); for (const urlGroup of allUrlGroups) { console.log(urlGroup.name, urlGroup.endpoints); } ``` -------------------------------- ### client.flowControl.getGlobalParallelism() Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the global parallelism settings for the QStash account. ```APIDOC ## client.flowControl.getGlobalParallelism() ### Description Retrieves the global parallelism configuration, including the maximum allowed parallelism and the current count. ``` -------------------------------- ### POST /v2/publish/... Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a message to a destination using an authentication token provided as a query parameter. ```APIDOC ## POST /v2/publish/... ### Description Publishes a message to a specified destination. This endpoint supports authentication via the qstash_token query parameter when header-based authentication is not feasible. ### Method POST ### Endpoint /v2/publish/... ### Parameters #### Query Parameters - **qstash_token** (string) - Required - The QStash authentication token. ``` -------------------------------- ### Publish message to QStash Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Execute this cURL command to send a JSON payload to your deployed Lambda function via QStash. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/https://urzdbfn4et56vzeasu3fpcynym0zerme.lambda-url.eu-west-1.on.aws" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Send Chat Completion Requests in Batches Source: https://upstash.com/docs/qstash/integrations/llm Use batch operations to send multiple LLM requests simultaneously. ```js import { Client, upstash } from "@upstash/qstash"; const client = new Client({ token: "", }); const result = await client.batchJSON([ { api: { name: "llm", provider: openai({ token: "_OPEN_AI_TOKEN_" }) }, body: { ... }, callback: "https://abc.requestcatcher.com", }, ... ]); console.log(result); ``` ```python from qstash import QStash from qstash.chat import upstash q = QStash("") result = q.message.batch_json( [ { "api":{"name": "llm", "provider": openai("")}, "body": {...}, "callback": "https://abc.requestcatcher.com", }, ... ] ) print(result) ``` ```shell curl "https://qstash.upstash.io/v2/batch" \ -X POST \ -H "Authorization: Bearer QSTASH_TOKEN" \ -H "Content-Type: application/json" \ -d '[ { "destination": "api/llm", "body": {...}, "callback": "https://abc.requestcatcher.com" }, ... ]' ``` -------------------------------- ### client.signing_key.rotate() Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Rotates the signing keys and returns the new current and next keys. ```APIDOC ## client.signing_key.rotate() ### Description Rotates the signing keys. The previous 'next' key becomes the 'current' key, and a new key is generated. ### Usage ```python from qstash import QStash client = QStash("") new_signing_key = client.signing_key.rotate() print(new_signing_key.current, new_signing_key.next) ``` ``` -------------------------------- ### client.flow_control.get_global_parallelism() Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves the global parallelism settings for the account. ```APIDOC ## client.flow_control.get_global_parallelism() ### Description Retrieves the current global parallelism configuration, including the maximum allowed and the current count. ``` -------------------------------- ### Configure Queue Parallelism with TypeScript Source: https://upstash.com/docs/qstash/overall/llms-txt Sets the parallelism level for a queue using the TypeScript client and displays the success response format. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.upsert({ parallelism: 1, }) ``` ```json { "success": true } ``` -------------------------------- ### POST /v2/publish/{url} Source: https://upstash.com/docs/qstash/features/delay Publishes a message to a specified URL with an optional delay. Use 'Upstash-Delay' for relative time or 'Upstash-Not-Before' for an absolute Unix timestamp. ```APIDOC ## POST /v2/publish/{url} ### Description Publishes a message to the specified destination URL. The delivery can be delayed using headers. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Headers - **Upstash-Delay** (string) - Optional - Relative delay duration (e.g., '10s', '1m', '2h'). - **Upstash-Not-Before** (integer) - Optional - Absolute Unix timestamp in seconds for delivery. ### Request Example curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Delay: 1m" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ``` -------------------------------- ### Implementing Error Handling and UI Loading States Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Updated server action with error handling and a client-side component to manage job execution states. ```typescript "use server" import { Client } from "@upstash/qstash"; const qstashClient = new Client({ token: process.env.QSTASH_TOKEN!, }); export async function startBackgroundJob() { try { const response = await qstashClient.publishJSON({ "url": "https://qstash-bg-job.vercel.app/api/long-task", body: { "hello": "world" } }); return response.messageId; } catch (error) { console.error(error); return null; } } ``` ```tsx "use client" import { startBackgroundJob } from "@/app/actions"; import { useState } from "react"; export default function Home() { const [loading, setLoading] = useState(false); const [msg, setMsg] = useState(""); async function handleClick() { setLoading(true); const messageId = await startBackgroundJob(); if (messageId) { setMsg(`Started job with ID ${messageId}`); } else { setMsg("Failed to start background job"); } setLoading(false); } return (
{loading &&
Loading...
} {msg &&

{msg}

}
); } ``` -------------------------------- ### QStash Flow Control Configuration JSON Source: https://upstash.com/docs/qstash/overall/llms-txt JSON structure for defining flow control parameters such as parallelism, rate, and period. ```json { "parallelism": 10, "rate": 100, "period": 60 } ``` -------------------------------- ### Retrieve Queue Information via cURL Source: https://upstash.com/docs/qstash/overall/llms-txt Retrieves the configuration and status of a specific queue using the QStash REST API. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` -------------------------------- ### POST /v2/schedules/{destination} Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule Creates a new schedule to send messages periodically to a specified destination URL or URL group. ```APIDOC ## POST /v2/schedules/{destination} ### Description Create a schedule to send messages periodically to a destination URL or URL group. ### Method POST ### Endpoint /v2/schedules/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - Destination URL or URL Group name. #### Header Parameters - **Upstash-Cron** (string) - Required - Cron expression defining the schedule frequency. - **Upstash-Schedule-Id** (string) - Optional - Custom ID for the schedule. - **Content-Type** (string) - Optional - MIME type of the message. - **Upstash-Method** (string) - Optional - HTTP method for the request (GET, POST, PUT, PATCH, DELETE). - **Upstash-Timeout** (string) - Optional - Maximum duration for the request (e.g., 5s, 2m, 1h). ``` -------------------------------- ### Rotate Signing Keys in Python Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Rotates the signing keys and returns the updated current and next keys. ```python from qstash import QStash client = QStash("") new_signing_key = client.signing_key.rotate() print(new_signing_key.current, new_signing_key.next) ``` -------------------------------- ### client.publishJSON() Source: https://upstash.com/docs/qstash/overall/llms-txt Publish a message with flow control settings including rate, parallelism, and period. ```APIDOC ## client.publishJSON() ### Description Combine rate, parallelism, and period to control message delivery. ### Method Signature `await client.publishJSON({ url: string, body: object, flowControl: { key: string, rate: number, parallelism: number, period: string } })` ``` -------------------------------- ### client.message.publish_json Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a JSON message to a specified URL using the QStash Python SDK, supporting callbacks and custom HTTP methods. ```APIDOC ## client.message.publish_json ### Description Publishes a JSON message to a specified URL. Supports defining a callback URL for long-running functions and specifying the HTTP method (default is POST). ### Parameters - **url** (string) - Required - The target URL to send the message to. - **body** (object) - Required - The JSON payload to send. - **callback** (string) - Optional - URL to receive the response. - **failure_callback** (string) - Optional - URL to receive failure notifications. - **method** (string) - Optional - The HTTP method to use (e.g., GET, POST). ``` -------------------------------- ### Verify Webhooks with Upstash SDK Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Uses the Receiver class from the @upstash/qstash package to validate request signatures. Requires QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY environment variables. ```typescript import { Receiver } from "@upstash/qstash" import type { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda" const receiver = new Receiver({ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY ?? "", nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY ?? "", }) export const handler = async ( event: APIGatewayProxyEvent ): Promise => { const signature = event.headers["upstash-signature"] const lambdaFunctionUrl = `https://${event.requestContext.domainName}` if (!signature) { return { statusCode: 401, body: JSON.stringify({ message: "Missing signature" }), } } try { await receiver.verify({ signature: signature, body: event.body ?? "", url: lambdaFunctionUrl, }) } catch (err) { return { statusCode: 401, body: JSON.stringify({ message: "Invalid signature" }), } } // Request is valid, perform business logic return { statusCode: 200, body: JSON.stringify({ message: "Request processed successfully" }), } } ``` -------------------------------- ### POST /v2/publish/{url} Source: https://upstash.com/docs/qstash/overall/apiexamples Publishes a message to a destination URL with optional retry configuration and callback URLs. ```APIDOC ## POST /v2/publish/{url} ### Description Publishes a message to the specified URL. Supports configuring retry attempts, custom retry delay expressions, and callback URLs for success or failure. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Header Parameters - **Upstash-Retries** (integer) - Optional - Number of retry attempts. - **Upstash-Retry-Delay** (string) - Optional - Mathematical expression for retry delay. - **Upstash-Callback** (string) - Optional - URL to receive success response. - **Upstash-Failure-Callback** (string) - Optional - URL to receive failure response. ### Request Body - **body** (object) - Required - The payload to send to the destination URL. ``` -------------------------------- ### Securing API Routes with Signature Verification Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Uses verifySignatureAppRouter to ensure that incoming requests to the API route originate from QStash. ```typescript import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" async function handler(request: Request) { const data = await request.json() for (let i = 0; i < 10; i++) { await fetch("https://firstqstashmessage.requestcatcher.com/test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, }) await new Promise((resolve) => setTimeout(resolve, 500)) } return Response.json({ success: true }) } export const POST = verifySignatureAppRouter(handler) ``` -------------------------------- ### Import Required Modules Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Standard library and PyJwt imports required for webhook processing. ```python import json import os import hmac import hashlib import base64 import time import jwt ``` -------------------------------- ### client.flowControl.get(key) Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the current status and configuration of a specific flow control key. ```APIDOC ## client.flowControl.get(key) ### Description Retrieves the current status and configuration of a specific flow control key, including wait list size, parallelism, and rate limits. ### Parameters - **key** (string) - Required - The unique identifier for the flow control key. ``` -------------------------------- ### Enqueue Messages to a Configured Queue Source: https://upstash.com/docs/qstash/features/queues Send messages to a queue after configuring its parallelism settings. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ 'https://qstash.upstash.io/v2/enqueue/my-queue/https://example.com' -d '{"message":"Hello, World!"}' ``` ```typescript const client = new Client({ token: "" }); const queue = QStashClient.queue({ queueName: "my-queue" }) await queue.enqueueJSON({ url: "https://example.com", body: { "Hello": "World" } }) ``` ```python from qstash import QStash client = QStash("") client.message.enqueue_json( queue="my-queue", url="https://example.com", body={ "Hello": "World", }, ) ``` -------------------------------- ### client.flow_control.get(key) Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves the current status and configuration of a specific flow control key. ```APIDOC ## client.flow_control.get(key) ### Description Retrieves the current status and configuration of a specific flow control key, including parallelism, rate limits, and pause status. ### Parameters - **key** (string) - Required - The unique identifier for the flow control key. ``` -------------------------------- ### List all schedules Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Retrieves a list of all schedules associated with the client. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); console.log(allSchedules); ``` -------------------------------- ### Configure URL Group Headers Source: https://upstash.com/docs/qstash/overall/llms-txt Sets default headers for a URL Group to apply them to all requests sent to that group. ```bash curl -X PATCH https://qstash.upstash.io/v2/topics/ \ -H "Authorization: Bearer " \ -d '{ "headers": { "Upstash-Header-Forward": ["true"], "Upstash-Retries": "3" } }' ``` -------------------------------- ### Create a schedule with cron expression Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Creates a schedule that triggers a destination URL based on a cron expression. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://my-api...", cron: "*/5 * * * *", }); ``` -------------------------------- ### Publishing an Anthropic Request Source: https://upstash.com/docs/qstash/integrations/anthropic Use publishJSON to send a single request to Anthropic via QStash with a callback URL. ```typescript import { anthropic, Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.publishJSON({ api: { name: "llm", provider: anthropic({ token: "" }) }, body: { model: "claude-3-5-sonnet-20241022", messages: [{ role: "user", content: "Summarize recent tech trends." }], }, callback: "https://example.com/callback", }); ``` -------------------------------- ### client.schedules.pause / client.schedules.resume Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Pauses or resumes an existing schedule. ```APIDOC ## client.schedules.pause / client.schedules.resume ### Description Updates the state of a schedule to either paused or active. ### Parameters - **schedule** (string) - Required - The ID of the schedule to modify. ``` -------------------------------- ### Publishing a Chat Completion Request Source: https://upstash.com/docs/qstash/integrations/llm Publishes a single chat completion request to an LLM provider via QStash. ```APIDOC ## Publish Chat Completion ### Description Publishes a single chat completion request to an LLM provider. Requires a callback URL for asynchronous response processing. ### Parameters - **api** (object) - Required - Configuration containing name: "llm" and the provider details. - **body** (object) - Required - The chat completion request body (e.g., model, messages). - **callback** (string) - Required - The URL to receive the asynchronous response. ``` -------------------------------- ### Unpin configuration Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Removes the pinned status for parallelism and rate settings independently. ```python from qstash import QStash client = QStash("") # Unpin parallelism and rate (can unpin independently) client.flow_control.unpin( "USER_GIVEN_KEY", {"parallelism": True, "rate": True}, ) ``` -------------------------------- ### Retry Delay Customization Strategies Source: https://upstash.com/docs/qstash/overall/llms-txt Mathematical expressions for defining retry backoff strategies, where 'retried' represents the count of failed attempts. ```text - `1000`: Fixed 1 second delay - `1000 * (1 + retried)`: Linear backoff - `pow(2, retried) * 1000`: Exponential backoff - `max(1000, pow(2, retried) * 100)`: Exponential with minimum 1s delay ``` -------------------------------- ### Publish a message to an endpoint Source: https://upstash.com/docs/qstash/overall/apiexamples Basic message publishing to a specific URL endpoint. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' ``` ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, ); # Async version is also available ``` -------------------------------- ### Access QStash Secrets via Cloudflare Secrets Store Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Use this pattern when managing credentials at the account level via the Cloudflare Secrets Store. Requires defining bindings in the worker environment. ```ts import { Receiver } from "@upstash/qstash"; export interface Env { QSTASH_CURRENT_SIGNING_KEY: SecretsStoreSecret; QSTASH_NEXT_SIGNING_KEY: SecretsStoreSecret; } export default { async fetch(request, env, ctx): Promise { const c = new Receiver({ currentSigningKey: await env.QSTASH_CURRENT_SIGNING_KEY.get(), nextSigningKey: await env.QSTASH_NEXT_SIGNING_KEY.get(), }); // Rest of the code }, }; ``` -------------------------------- ### Publish a message with custom headers Source: https://upstash.com/docs/qstash/howto/publishing Demonstrates sending a JSON payload with custom headers using cURL, TypeScript, and Python. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H 'Upstash-Forward-My-Header: my-value' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://example.com", body: { "hello": "world" }, headers: { "my-header": "my-value" }, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "my-header": "my-value", }, ); ``` -------------------------------- ### Configure Failure Callbacks Source: https://upstash.com/docs/qstash/howto/handling-failures Specify a failure callback URL when publishing a message to handle delivery errors programmatically. ```bash curl -X POST \ https://qstash.upstash.io/v2/publish/ \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Failure-Callback: ' \ -d '{ "hello": "world" }' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, failureCallback: "https://my-callback...", }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, failure_callback="https://my-callback...", ) ``` -------------------------------- ### POST /v2/publish/{url} Source: https://upstash.com/docs/qstash/features/callbacks Publishes a message to a destination URL with an optional callback URL for delivery status notifications. ```APIDOC ## POST /v2/publish/{url} ### Description Publishes a message to the specified URL. To receive a callback, include the `Upstash-Callback` header. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Path Parameters - **url** (string) - Required - The destination URL for the message. #### Request Headers - **Authorization** (string) - Required - Bearer - **Upstash-Callback** (string) - Optional - The URL to receive the callback notification. ### Request Example ```bash curl -X POST \ https://qstash.upstash.io/v2/publish/https://my-api... \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'Upstash-Callback: ' \ -d '{ "hello": "world" }' ``` ``` -------------------------------- ### POST /v2/publish/{url} Source: https://upstash.com/docs/qstash/overall/llms-txt Publishes a JSON message to a specified URL with optional flow control settings for rate and parallelism limits. ```APIDOC ## POST /v2/publish/{url} ### Description Publishes a JSON message to the specified destination URL. ### Method POST ### Endpoint /v2/publish/{url} ### Request Headers - **Authorization** (string) - Required - Bearer - **Upstash-Flow-Control-Key** (string) - Optional - Key for flow control - **Upstash-Flow-Control-Value** (string) - Optional - Configuration string (e.g., parallelism=5,rate=10,period=1m) ### Request Body - **message** (object) - Required - The JSON payload to send ``` -------------------------------- ### POST /v2/schedules/{destination} Source: https://upstash.com/docs/qstash/features/schedules Creates a new schedule to publish messages at a specified cron interval. This can be targeted at a URL, a URL group, or a queue. ```APIDOC ## POST /v2/schedules/{destination} ### Description Creates a new schedule to publish messages at a specified cron interval. The destination can be a URL, a URL group name, or a URL group ID. ### Method POST ### Endpoint https://qstash.upstash.io/v2/schedules/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - The URL, URL group name, or URL group ID to publish to. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Upstash-Cron** (string) - Required - The cron expression defining the schedule. - **Upstash-Queue-Name** (string) - Optional - The name of the queue to add the message to. - **Upstash-Schedule-Id** (string) - Optional - An explicit ID to assign to the schedule or to overwrite an existing one. ### Request Body - **body** (object) - Optional - The payload to be sent with the scheduled message. ``` -------------------------------- ### Publish with Callback URLs Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Configures success and failure callbacks for long-running tasks and specifies the HTTP method for the request. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, callback: "https://my-callback...", failureCallback: "https://my-failure-callback...", method: "GET", }); ```