### Initialize and Configure Next.js Project Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Commands to create a new Next.js application, 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 Required Packages Source: https://upstash.com/docs/qstash/recipes/periodic-data-updates Install the necessary Upstash QStash and Redis client libraries. ```bash npm install @upstash/qstash @upstash/redis ``` -------------------------------- ### Install QStash Python Client Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Install the QStash Python package using pip. This is the first step to using QStash in your Python projects. ```bash pip install qstash ``` -------------------------------- ### Initialize AWS CDK Project and Install Dependencies Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Use the AWS CDK to create a new Node.js project and install the @upstash/qstash SDK. This sets up the basic structure for an AWS Lambda application. ```bash mkdir my-app cd my-app cdk init app -l typescript npm i esbuild @upstash/qstash mkdir lambda touch lambda/index.ts ``` -------------------------------- ### Install Upstash QStash Library Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Install the Upstash QStash library for Node.js using npm. This library is required for handling QStash webhooks. ```bash npm install @upstash/qstash ``` -------------------------------- ### Deploying to Vercel via CLI Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Commands to install the Vercel CLI and initiate a deployment. ```bash npm install -g vercel ``` ```bash vercel ``` -------------------------------- ### Run QStash CLI with NPX Source: https://upstash.com/docs/qstash/howto/local-development Start the local development server using NPX. You can optionally specify a custom port. ```javascript npx @upstash/qstash-cli dev // Start on a different port npx @upstash/qstash-cli dev -port=8081 ``` -------------------------------- ### Install Vercel CLI Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Install the Vercel Command Line Interface globally. This tool is used for deploying applications to Vercel. ```bash npm install -g vercel ``` -------------------------------- ### Start localtunnel Source: https://upstash.com/docs/qstash/howto/local-tunnel Run this command to expose your local development server to the internet. Replace `3000` with your application's port. ```bash npx localtunnel --port 3000 ``` -------------------------------- ### Start ngrok tunnel Source: https://upstash.com/docs/qstash/howto/local-tunnel Start an ngrok tunnel to forward traffic to your local application. Replace `3000` with your application's port. ```bash $ ngrok http 3000 ``` -------------------------------- ### Bundle Lambda Function with Makefile Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Automates the installation of dependencies and packaging of the Lambda function into a zip file. ```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 ./ ``` -------------------------------- ### Create a schedule that runs every 5 minutes Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules This example demonstrates how to create a new schedule that executes a task every 5 minutes. ```APIDOC ## POST /schedules/create ### Description Creates a new schedule that runs at a specified interval. ### Method POST ### Endpoint /schedules/create ### Parameters #### Request Body - **destination** (string) - Required - The URL or URL group to send the request to. - **cron** (string) - Required - The cron syntax defining the schedule's execution time. ### Request Example ```json { "destination": "https://my-api...", "cron": "*/5 * * * *" } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. - **cron** (string) - The cron syntax used for the schedule. - **destination** (string) - The destination URL or URL group. #### Response Example ```json { "scheduleId": "schedule-id-123", "cron": "*/5 * * * *", "destination": "https://my-api..." } ``` ``` -------------------------------- ### QStash JWT Header Example Source: https://upstash.com/docs/qstash/features/security This is an example of the JWT header used in the Upstash-Signature. The algorithm is HS256 and the type is JWT. ```json { "alg": "HS256", "typ": "JWT" } ``` -------------------------------- ### Install Upstash Redis Package Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Install the necessary Python package for interacting with Upstash Redis. This command ensures the redis client is available. ```bash pip install upstash-redis ``` -------------------------------- ### GET /v2/schedules Source: https://upstash.com/docs/qstash/overall/apiexamples List all schedules currently configured in the QStash service. ```APIDOC ## GET /v2/schedules ### Description List all schedules. ### Method GET ### Endpoint https://qstash.upstash.io/v2/schedules ### Request Example curl https://qstash.upstash.io/v2/schedules -H "Authorization: Bearer XXX" ``` -------------------------------- ### Initialize QStash Receiver Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Initialize the QStash Receiver with the current and next signing keys obtained from environment variables. This setup is necessary before verifying signatures. ```typescript const receiver = new Receiver({ currentSigningKey: env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: env.QSTASH_NEXT_SIGNING_KEY, }); ``` -------------------------------- ### Handling Callbacks in Next.js Source: https://upstash.com/docs/qstash/features/callbacks Example implementation of a Next.js API route to process incoming QStash callbacks, including signature verification. ```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, }, }; ``` -------------------------------- ### Create a schedule to a URL Group that runs every minute Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules This example illustrates creating a schedule that triggers every minute and targets a URL group. ```APIDOC ## POST /schedules/create ### Description Creates a schedule that runs every minute and directs requests to a specified URL group. ### Method POST ### Endpoint /schedules/create ### Parameters #### Request Body - **destination** (string) - Required - The name of the URL group. - **cron** (string) - Required - The cron syntax for minute-based execution. ### Request Example ```json { "destination": "my-url-group", "cron": "* * * * *" } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. - **cron** (string) - The cron syntax used. - **destination** (string) - The URL group name. #### Response Example ```json { "scheduleId": "schedule-id-789", "cron": "* * * * *", "destination": "my-url-group" } ``` ``` -------------------------------- ### Publish a Chat Completion Request Source: https://upstash.com/docs/qstash/integrations/llm Use these examples to send a single chat completion request to an OpenAI-compatible provider via QStash. ```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); ``` ```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) ``` -------------------------------- ### QStash JWT Payload Example Source: https://upstash.com/docs/qstash/features/security This is an example of the JWT payload included in the Upstash-Signature. It contains issuer, subject, expiration, not before, issued at, JWT ID, and a hashed request body. ```json { "iss": "Upstash", "sub": "https://qstash-remote.requestcatcher.com/test", "exp": 1656580612, "nbf": 1656580312, "iat": 1656580312, "jti": "jwt_67kxXD6UBAk7DqU6hzuHMDdXFXfP", "body": "qK78N0k3pNKI8zN62Fq2Gm-_LtWkJk1z9ykio3zZvY4=" } ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control 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 ### 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 ```json { "parallelismMax": 1000, "parallelismCount": 500 } ``` ``` -------------------------------- ### Get Flow Control Key Info with cURL Source: https://upstash.com/docs/qstash/features/flowcontrol Use a GET request to the QStash API endpoint `/v2/flowControl/{key}` to retrieve information about a specific flow control key. Include your authorization token in the header. ```bash curl -X GET https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY \ -H "Authorization: Bearer " ``` -------------------------------- ### Create a schedule that runs every hour and sends the result to a callback URL Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules This example shows how to create a schedule that runs hourly and utilizes callback URLs for success and failure notifications. ```APIDOC ## POST /schedules/create ### Description Creates a schedule with hourly execution and specifies callback URLs for handling responses. ### Method POST ### Endpoint /schedules/create ### Parameters #### Request Body - **destination** (string) - Required - The URL to send the request to. - **cron** (string) - Required - The cron syntax for hourly execution. - **callback** (string) - Optional - The URL to send the results to upon successful execution. - **failureCallback** (string) - Optional - The URL to send the results to upon failure. ### Request Example ```json { "destination": "https://my-api...", "cron": "0 * * * *", "callback": "https://my-callback...", "failureCallback": "https://my-failure-callback..." } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. - **cron** (string) - The cron syntax used. - **destination** (string) - The destination URL. - **callback** (string) - The success callback URL. - **failureCallback** (string) - The failure callback URL. #### Response Example ```json { "scheduleId": "schedule-id-456", "cron": "0 * * * *", "destination": "https://my-api...", "callback": "https://my-callback...", "failureCallback": "https://my-failure-callback..." } ``` ``` -------------------------------- ### Enqueue a message to a queue Source: https://upstash.com/docs/qstash/features/queues Examples of how to enqueue a message to a specific queue using cURL, TypeScript, and Python. ```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", }, ) ``` -------------------------------- ### Get Signing 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 ### Parameters #### Query Parameters - **qstash_token** (string) - Required - QStash authentication token passed as a query parameter ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **current** (string) - The current signing key. - **next** (string) - The next signing key. #### Response Example ```json { "current": "your_current_signing_key", "next": "your_next_signing_key" } ``` ``` -------------------------------- ### Enqueue a Chat Completion Request Source: https://upstash.com/docs/qstash/integrations/llm Use these examples to add a chat completion request to a specific QStash queue for asynchronous processing. ```JavaScript import { Client, upstash } from "@upstash/qstash"; const client = new Client({ token: "", }); const result = await client.queue({ queueName: "queue-name" }).enqueueJSON({ 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); ``` ```Python from qstash import QStash from qstash.chat import upstash q = QStash("") result = q.message.enqueue_json( queue="queue-name", 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) ``` -------------------------------- ### Get Queue Details with Python Source: https://upstash.com/docs/qstash/features/queues Use the QStash Python client to retrieve the configuration details of a specific queue. This allows you to check settings like parallelism. ```python from qstash import QStash client = QStash("") client.queue.get("my-queue") ``` -------------------------------- ### Get Flow Control Key OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-flow-control-key Defines the GET /v2/flowControl/{flowControlKey} endpoint and the associated FlowControlKey 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.upstash.io 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 ``` -------------------------------- ### Start background job with QStash client Source: https://upstash.com/docs/qstash/features/background-jobs This Next.js API route uses the QStash client to publish a job to a specified email API endpoint. Ensure you replace 'YOUR_TOKEN' with your actual 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 }); } ``` -------------------------------- ### Get Queue Details Source: https://upstash.com/docs/qstash/features/queues Retrieve the current configuration and status of a specific queue, including its parallelism settings. ```bash curl https://qstash.upstash.io/v2/queues/my-queue \ -H "Authorization: Bearer " ``` -------------------------------- ### Get Global Parallelism (Python) Source: https://upstash.com/docs/qstash/features/flowcontrol This Python snippet demonstrates how to fetch global parallelism information using the QStash library. Initialize the client with your QStash token before making the call. ```python from qstash import QStash client = QStash("") info = client.flow_control.get_global_parallelism() print(info) # GlobalParallelismInfo( # parallelism_max=500, # parallelism_count=42 # ) ``` -------------------------------- ### GET /url_group/list Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Lists all available URL groups. ```APIDOC ## GET /url_group/list ### Description Returns a list of all URL groups defined in the account. ``` -------------------------------- ### GET /v2/schedules Source: https://upstash.com/docs/qstash/howto/delete-schedule Retrieves a list of all schedules associated with the account. ```APIDOC ## GET /v2/schedules ### Description Retrieves a list of all schedules for the authenticated user. ### Method GET ### Endpoint https://qstash.upstash.io/v2/schedules ``` -------------------------------- ### Delivered Message Structure Source: https://upstash.com/docs/qstash/howto/publishing Example of the resulting body and headers delivered to the destination API. ```json // body { "hello": "world" } // headers My-Header: my-value Content-Type: application/json ``` -------------------------------- ### GET /url-groups Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Lists all URL groups available in the account. ```APIDOC ## GET /url-groups ### Description Returns a list of all defined URL groups and their associated endpoints. ### Method GET ``` -------------------------------- ### Get a Schedule Source: https://upstash.com/docs/qstash/api-reference/schedules/get-a-schedule Retrieves the details of a specific schedule by 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. ### Responses #### 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 - **label** (string) - The label 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 - **lastScheduleStates** (object) - The states of the last scheduled messages #### Error Response (404) - **error** (string) - Error message ``` -------------------------------- ### Get Message Logs with Typescript SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve message logs using the QStash Typescript SDK. Initialize the client with your QStash token. ```typescript const client = new Client({ token: "" }); const logs = await client.logs() ``` -------------------------------- ### Get Message Logs with Python SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve message logs using the QStash Python SDK. Initialize the client with your QStash token. An async version is also available. ```python from qstash import QStash client = QStash("") client.event.list() # Async version is also available ``` -------------------------------- ### Initialize Fly.io Application Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Use the flyctl launch command to scan 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` ``` -------------------------------- ### Define Upstash-Delay Header Format Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Examples of valid values for the Upstash-Delay header to schedule message delivery. ```text 50s ``` ```text 1d10h30m ``` ```text 10h ``` ```text 1d ``` -------------------------------- ### List All URL Groups Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Fetch a list of all configured URL groups. This can be used to get an overview of your routing configurations. ```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); } ``` -------------------------------- ### 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 /url_group/get Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Retrieves the details of a specific URL group by its name. ```APIDOC ## GET /url_group/get ### Description Fetches the configuration and endpoints of a specific URL group. ### Parameters #### Query Parameters - **url_group** (string) - Required - The name of the URL group to retrieve. ``` -------------------------------- ### Get Global Parallelism Settings Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Fetch the current global parallelism settings for your QStash instance. This provides insight into the overall message processing capacity. Initialize the QStash client with your token before use. ```python from qstash import QStash client = QStash("") info = client.flow_control.get_global_parallelism() print(info.parallelism_max) print(info.parallelism_count) ``` -------------------------------- ### Get Flow Control Key Info in Python Source: https://upstash.com/docs/qstash/features/flowcontrol Fetch flow control key details using the QStash Python client. Initialize the client with your QStash token and call the `flow_control.get()` method with the key name. ```python from qstash import QStash client = QStash("") info = client.flow_control.get("USER_GIVEN_KEY") print(info) ``` -------------------------------- ### Create Cloudflare Worker Project with npm Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Use npm to create a new Cloudflare worker project. This command installs the necessary packages and sets up the project structure. ```shell npm create cloudflare@latest ``` -------------------------------- ### GET /v2/logs Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve logs for all messages that have been published, with optional filtering capabilities. ```APIDOC ## GET /v2/logs ### Description Retrieve logs for all messages that have been published. ### Method GET ### Endpoint https://qstash.upstash.io/v2/logs ### Request Example curl https://qstash.upstash.io/v2/logs -H "Authorization: Bearer XXX" ``` -------------------------------- ### Get a URL Group Source: https://upstash.com/docs/qstash/api-reference/url-groups/get-a-url-group Retrieve details of a specific URL Group by its name. ```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. ### 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 a Message Source: https://upstash.com/docs/qstash/api-reference/messages/get-a-message Retrieve details of a specific message using its unique 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. - **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. #### Response Example ```json { "messageId": "msg_abc123", "url": "https://example.com/webhook", "topicName": "my-topic", "endpointName": "default", "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", "label": "user-data", "flowControlKey": "fc_key_1", "rate": 100, "period": 60, "parallelism": 10 } ``` #### Error Response (404) - **error** (string) - Error message #### Response Example ```json { "error": "Message not found" } ``` ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the global parallelism settings and current usage counts. ```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); ``` -------------------------------- ### Get a schedule by ID Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Retrieves details for a specific schedule using its unique identifier. ```python from qstash import QStash client = QStash("") schedule = client.schedule.get("") print(schedule.cron) ``` -------------------------------- ### Get Queue Details with TypeScript Source: https://upstash.com/docs/qstash/features/queues Fetch the details of a queue, such as its parallelism, using the QStash TypeScript client library. This is useful for monitoring queue configurations. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) const res = await queue.get() ``` -------------------------------- ### Run QStash CLI Executable Source: https://upstash.com/docs/qstash/howto/local-development Execute the binary directly after downloading and extracting it from the artifact repository. ```bash $ ./qstash dev ``` -------------------------------- ### GET /messages/{msgId} Source: https://upstash.com/docs/qstash/sdks/ts/examples/messages Retrieves a specific message that is currently in the process of being delivered or retried. ```APIDOC ## GET /messages/{msgId} ### Description Retrieves a message by its ID. Note that messages are removed from the database shortly after delivery, so this is intended for messages currently in the process of being delivered or retried. ### Method GET ### Endpoint /messages/{msgId} ### Parameters #### Path Parameters - **msgId** (string) - Required - The unique identifier of the message. ``` -------------------------------- ### QStash Dev Command Help Source: https://upstash.com/docs/qstash/howto/local-development Displays help information for the `dev` command, including available flags for port and quota configuration. ```bash Usage of dev: -port int The port to start HTTP server at [env QSTASH_DEV_PORT] (default 8080) -quota string The quota of users [env QSTASH_DEV_QUOTA] (default "payg") ``` -------------------------------- ### GET /v2/logs Source: https://upstash.com/docs/qstash/api-reference/logs/list-logs Retrieves a paginated list of logs for published messages with optional filtering parameters. ```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** (string) - Optional - Filter logs by the label of the message assigned by the user ### Response #### Success Response (200) - **cursor** (string) - A cursor which you can use in subsequent requests to paginate through all logs. If no cursor is returned, you have reached the end of the logs. - **logs** (array) - List of log entries ``` -------------------------------- ### Initialize Python Project for AWS Lambda Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Sets up a new directory and creates the main Python file for an AWS Lambda project. This is the initial step for building the webhook receiver. ```bash mkdir aws-lambda cd aws-lambda touch lambda_function.py ``` -------------------------------- ### Get Flow Control Key Information Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieve detailed information for a specific flow control key. This includes its current state, wait list size, parallelism limits and counts, rate limits and counts, and pinning status. Ensure you have initialized the QStash client with your token. ```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) ``` -------------------------------- ### Get all events with pagination using cursor in Python Source: https://upstash.com/docs/qstash/sdks/py/examples/events Iterates through all available events by continuously updating the cursor until no more results are returned. ```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 ``` -------------------------------- ### Create Cloudflare Worker Project with yarn Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Use yarn to create a new Cloudflare worker project. This command installs the necessary packages and sets up the project structure. ```shell yarn create cloudflare@latest ``` -------------------------------- ### Get a schedule by schedule id Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Retrieves the details of a specific schedule using its unique ID. ```APIDOC ## 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. #### Response Example ```json { "scheduleId": "scheduleId", "cron": "* * * * *", "destination": "https://example.com", "isPaused": false } ``` ``` -------------------------------- ### List All Schedules with Python SDK Source: https://upstash.com/docs/qstash/overall/apiexamples List all schedules using the QStash Python SDK. Initialize the client with your QStash token. An async version is also available. ```python from qstash import QStash client = QStash("") client.schedule.list() # Async version is also available ``` -------------------------------- ### Get Global Parallelism (cURL) Source: https://upstash.com/docs/qstash/features/flowcontrol Execute this cURL command to retrieve global parallelism data via the Upstash QStash REST API. Replace with your actual Qstash token. ```bash curl -X GET https://qstash.upstash.io/v2/globalParallelism \ -H "Authorization: Bearer " ``` -------------------------------- ### Get Message Logs with cURL Source: https://upstash.com/docs/qstash/overall/apiexamples Retrieve logs for all published messages using cURL. Ensure you include your authorization token. ```shell curl https://qstash.upstash.io/v2/logs \ -H "Authorization: Bearer XXX" ``` -------------------------------- ### GET /v2/dlq/{dlqId} Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Retrieves the details of a specific message currently residing in 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. ``` -------------------------------- ### Initialize Synchronous QStash Client Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Instantiate the synchronous QStash client with your QStash token. This client is used for making direct API calls. ```python from qstash import QStash client = QStash("") client.message.publish_json(...) ``` -------------------------------- ### Get a single flow control key Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the current status and configuration metrics for 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); ``` -------------------------------- ### Create QStash Schedule with SDK Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Automate the creation of QStash schedule jobs using the QStash Python SDK. Replace 'YOUR_URL.vercel.app' with your deployed endpoint URL and '' with your QStash token. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="https://YOUR_URL.vercel.app/api", cron="0 12 * * *", ) ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Create a new directory for your Python application. This command initializes the project folder. ```bash mkdir clean-db-cron ``` -------------------------------- ### Deploy Application to Fly.io 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 ``` -------------------------------- ### Run QStash CLI with Docker Source: https://upstash.com/docs/qstash/howto/local-development Pull and run the QStash CLI using the official Docker image from the 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 ``` -------------------------------- ### Configure QStash Environment Variables Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Set the required signing keys as secrets in the Fly.io environment. ```bash flyctl secrets set QSTASH_CURRENT_SIGNING_KEY=... flyctl secrets set QSTASH_NEXT_SIGNING_KEY=... ``` -------------------------------- ### Publish with Callback URLs Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Configures callback and failure callback URLs for long-running tasks. Setting the method to GET changes the request type from the default POST. ```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", }); ``` -------------------------------- ### List All Schedules with Typescript SDK Source: https://upstash.com/docs/qstash/overall/apiexamples List all schedules using the QStash Typescript SDK. Initialize the client with your QStash token. ```typescript const client = new Client({ token: "" }); const scheds = await client.schedules.list(); ``` -------------------------------- ### Resume Queue Source: https://upstash.com/docs/qstash/api-reference/queues/resume-queue 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. ```APIDOC ## POST /v2/queues/{queueName}/resume ### Description Resumes a queue to start the delivery of enqueued messages, beginning with the earliest undelivered message. If the queue is already active, this action has no effect. ### Method POST ### Endpoint /v2/queues/{queueName}/resume ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to resume. ### Request Example ```json { "example": "No request body needed for this endpoint." } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the queue was resumed successfully. #### Response Example ```json { "message": "Queue resumed successfully" } ``` #### Error Response (400) - **error** (string) - Provides details about the error, such as an invalid queue name. #### Error Response Example ```json { "error": "Queue name is invalid. Queue names can only contain alphanumeric characters, hyphens, periods, and underscores." } ``` ``` -------------------------------- ### Verify incoming requests with multi-region support Source: https://upstash.com/docs/qstash/howto/multi-region Pass the upstash-region header to the verify method to ensure the correct signing keys are used 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, }); ``` -------------------------------- ### Get Global Parallelism (TypeScript) Source: https://upstash.com/docs/qstash/features/flowcontrol Use this snippet to retrieve the global parallelism limits and current usage with the Upstash QStash TypeScript client. Ensure you have initialized the client with your QSTASH_TOKEN. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.getGlobalParallelism(); console.log(info); // { // parallelismMax: 500, // parallelismCount: 42 // } ``` -------------------------------- ### Get URL Group by Name Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Retrieve a specific URL group by its name. This is useful for inspecting the group's configuration and endpoints. ```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 Retrieve a specific URL group using its name. The output includes the group's name and its configured endpoints. ```python from qstash import QStash client = QStash("") url_group = client.url_group.get("my-url-group") print(url_group.name, url_group.endpoints) ``` -------------------------------- ### Import Necessary Libraries for Lambda Handler Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Imports standard Python libraries and the `jwt` library for handling JWT verification. Ensure `PyJwt` is installed during the zipping stage for AWS Lambda. ```python import json import os import hmac import hashlib import base64 import time import jwt ``` -------------------------------- ### Get global parallelism Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves the current global parallelism settings, showing the maximum allowed concurrent messages across all flow control keys. ```APIDOC ## Get 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 number of concurrently processed messages globally. #### Response Example ```json { "parallelism_max": 100, "parallelism_count": 5 } ``` ``` -------------------------------- ### Initialize Asynchronous QStash Client Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Instantiate the asynchronous QStash client with your QStash token. This client should be used within an asyncio event loop for non-blocking operations. ```python import asyncio from qstash import AsyncQStash async def main(): client = AsyncQStash("") await client.message.publish_json(...) asyncio.run(main()) ``` -------------------------------- ### Get a single flow control key Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Retrieves detailed information about a specific flow control key, including its current state and configuration limits. ```APIDOC ## Get a single flow control 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 unique identifier for the flow control key. ### Response #### Success Response (200) - **key** (string) - The flow control key identifier. - **wait_list_size** (integer) - The number of messages currently waiting to be processed. - **parallelism_max** (integer) - The maximum allowed concurrent messages. - **parallelism_count** (integer) - The current number of concurrently processed messages. - **rate_max** (integer) - The maximum number of messages allowed within the specified rate period. - **rate_count** (integer) - The current number of messages processed within the rate 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 message delivery for this key is currently paused. - **is_pinned_parallelism** (boolean) - Indicates if the parallelism configuration is pinned. - **is_pinned_rate** (boolean) - Indicates if the rate configuration is pinned. #### Response Example ```json { "key": "USER_GIVEN_KEY", "wait_list_size": 0, "parallelism_max": 10, "parallelism_count": 0, "rate_max": 100, "rate_count": 0, "rate_period": 60, "rate_period_start": 1678886400, "is_paused": false, "is_pinned_parallelism": false, "is_pinned_rate": false } ``` ``` -------------------------------- ### Configure URL Group Headers via API Source: https://upstash.com/docs/qstash/howto/webhook Configure default headers for a URL Group to automatically apply them to all requests sent to that group. This example sets Upstash-Header-Forward to true and Upstash-Retries to 3. ```bash curl -X PATCH https://qstash.upstash.io/v2/topics/ \ -H "Authorization: Bearer " \ -d '{ "headers": { "Upstash-Header-Forward": ["true"], "Upstash-Retries": "3" } }' ``` -------------------------------- ### GET /v2/globalParallelism Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-global-parallelism Retrieves the current global parallelism usage, including the maximum configured limit and the current count of messages running in parallel. ```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 #### Response Example { "parallelismMax": 100, "parallelismCount": 12 } ``` -------------------------------- ### Get a single flow control key Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Retrieves the current flow control settings for a specific key, including parallelism, rate limits, and pause status. ```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. #### Response Example ```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 } ``` ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Change the current directory to the newly created project folder. This command is used to enter the project's root. ```bash cd clean-db-cron ``` -------------------------------- ### Start Background Job Button (Next.js) Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Frontend component for a Next.js app that triggers a background job via an async action. It manages loading states and displays messages upon job initiation or failure. ```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}

}
); } ``` -------------------------------- ### Verify Signature with QStash SDK (Golang) Source: https://upstash.com/docs/qstash/howto/signature Implement signature verification in Go using the qstash-go SDK. Initialize a new receiver with your signing keys and use the Verify method. ```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 ``` -------------------------------- ### Get Flow Control Key Information Source: https://upstash.com/docs/qstash/features/flowcontrol Provides details on how to retrieve the current state and metrics for a specific flow control key using the client and cURL. ```APIDOC ## Get a single flow control key Returns the current state and metrics for one flow control key. ### TypeScript Example ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info); // { // flowControlKey: "USER_GIVEN_KEY", // waitListSize: 5, // parallelismMax: 10, // parallelismCount: 3, // rateMax: 100, // rateCount: 42, // ratePeriod: 60, // ratePeriodStart: 1708000000, // isPaused: false, // isPinnedParallelism: false, // isPinnedRate: false // } ``` ### Python Example ```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 # ) ``` ### cURL Example ```bash curl -X GET https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY \ -H "Authorization: Bearer " ``` ### Response Fields | Field | Description | | --------------------- | -------------------------------------------------------- | | `flowControlKey` | The flow control key name | | `waitListSize` | Number of messages currently waiting in the queue | | `parallelismMax` | Configured maximum concurrent messages (if set) | | `parallelismCount` | Number of messages currently running in parallel | | `rateMax` | Configured maximum messages per rate period (if set) | | `rateCount` | Number of messages dispatched in the current rate period | | `ratePeriod` | Rate period length in seconds | | `ratePeriodStart` | Unix timestamp when the current rate period started | | `isPaused` | Whether delivery is currently paused for this key | | `isPinnedParallelism` | Whether the parallelism configuration is pinned | | `isPinnedRate` | Whether the rate configuration is pinned | ``` -------------------------------- ### Get Flow Control Key Info in TypeScript Source: https://upstash.com/docs/qstash/features/flowcontrol Retrieve the current state and metrics for a specific flow control key using the `client.flowControl.get()` method. Requires the QStash client to be initialized with a token. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info); ``` -------------------------------- ### Deno Deploy Handler for QStash Webhooks Source: https://upstash.com/docs/qstash/quickstarts/deno-deploy Use this code to set up a Deno deploy handler that verifies incoming QStash webhook signatures. Ensure QStash signing keys are configured as environment variables. ```typescript 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 }); }); ``` -------------------------------- ### GET /dlq/listMessages Source: https://upstash.com/docs/qstash/sdks/ts/examples/dlq Retrieves messages from the Dead Letter Queue. Supports pagination via cursors, result limiting, ordering, and filtering by URL or specific DLQ IDs. ```APIDOC ## GET /dlq/listMessages ### Description Fetch messages from the DLQ. Supports pagination and filtering. ### Parameters #### Query Parameters - **cursor** (string) - Optional - Pagination cursor - **count** (number) - Optional - Number of messages to return - **order** (string) - Optional - Sort order (e.g., "latestFirst") - **filter** (object) - Optional - Filter criteria (e.g., url) - **dlqIds** (array) - Optional - List of specific DLQ IDs to fetch ``` -------------------------------- ### Retrieve QStash Signing Keys Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Fetches the current and next signing keys for the authenticated client. ```python from qstash import QStash client = QStash("") signing_key = client.signing_key.get() print(signing_key.current, signing_key.next) ``` -------------------------------- ### QStash Dev Server User 2 Credentials Source: https://upstash.com/docs/qstash/howto/local-development Environment variables for User 2 to connect to the QStash development server. Use these for testing. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjEiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_7GVPjvuwsfqF65iC8fSrs1dfYruM" QSTASH_NEXT_SIGNING_KEY="sig_5NoELc3EFnZn4DVS5bDs2Nk4b7Ua" ``` -------------------------------- ### QStash Dev Server User 1 Credentials Source: https://upstash.com/docs/qstash/howto/local-development Environment variables for User 1 to connect to the QStash development server. Use these for testing. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJkZWZhdWx0VXNlciIsIlBhc3N3b3JkIjoiZGVmYXVsdFBhc3N3b3JkIn0=" QSTASH_CURRENT_SIGNING_KEY="sig_7kYjw48mhY7kAjqNGcy6cr29RJ6r" QSTASH_NEXT_SIGNING_KEY="sig_5ZB6DVzB1wjE8S6rZ7eenA8Pdnhs" ``` -------------------------------- ### Deploy to Vercel Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Deploy your application to Vercel using the Vercel CLI. This command initiates the deployment process. ```bash vercel ``` -------------------------------- ### Create a queue with parallelism Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Initializes a queue with a specified parallelism level using the QStash client. ```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(); ``` -------------------------------- ### Get Flow Control Key Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-flow-control-key Retrieves details of a specific Flow Control key. This is useful for monitoring message queues and understanding current flow control configurations. ```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 ### Responses #### 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 ### Request Example (No request body for GET request) ### Response Example (200 OK) ```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 } ``` ### Response Example (404 Not Found) ```json { "error": "Flow Control key not found" } ``` ``` -------------------------------- ### Get a Specific DLQ Message Source: https://upstash.com/docs/qstash/sdks/py/examples/dlq Retrieve a single message from the Dead Letter Queue using its unique DLQ ID. Ensure you have your QStash token and the correct DLQ ID. ```python from qstash import QStash client = QStash("") msg = client.dlq.get("") ``` -------------------------------- ### Configure ngrok authentication Source: https://upstash.com/docs/qstash/howto/local-tunnel Add your ngrok authtoken to the ngrok configuration file to connect your account. ```bash ngrok config add-authtoken XXX ``` -------------------------------- ### Reset Rate Count Source: https://upstash.com/docs/qstash/features/flowcontrol Reset the rate count and terminate the current rate period for a flow control key, forcing the next delivery to start a new period. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.flowControl.resetRate("USER_GIVEN_KEY"); ``` ```python from qstash import QStash client = QStash("") client.flow_control.reset_rate("USER_GIVEN_KEY") ``` ```bash curl -X POST https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/resetRate \ -H "Authorization: Bearer " ``` -------------------------------- ### Create a schedule that runs every 5 minutes Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Initializes a schedule with a specific destination URL and cron expression. ```python from qstash import QStash client = QStash("") schedule_id = client.schedule.create( destination="https://my-api...", cron="*/5 * * * *", ) print(schedule_id) ``` -------------------------------- ### Get a Message Source: https://upstash.com/docs/qstash/api-reference/messages/get-a-message Retrieve details of a specific message. Note that messages are removed from the database shortly after delivery and cannot be retrieved afterward. This endpoint is for messages currently in the process of delivery or retries. ```APIDOC ## GET /messages/{messageId} ### Description Retrieve details of a specific message. ### Method GET ### Endpoint /messages/{messageId} ### Parameters #### Path Parameters - **messageId** (string) - Required - The ID of the message to retrieve. ### Response #### Success Response (200) - **messageId** (string) - The ID of the message. - **body** (object) - The message body. - **contentType** (string) - The content type of the message. - **deduplicationId** (string) - The deduplication ID of the message. - **delay** (integer) - The delay in seconds for scheduled messages. - **notBefore** (integer) - The timestamp in seconds before which the message should not be delivered. - **retries** (integer) - The number of retries remaining for the message. - **tags** (array) - An array of tags associated with the message. - **topic** (string) - The topic of the message. - **url** (string) - The URL to which the message will be sent. #### Response Example ```json { "messageId": "msg_abc123", "body": { "key": "value" }, "contentType": "application/json", "deduplicationId": "dedup_xyz789", "delay": 0, "notBefore": 0, "retries": 3, "tags": ["tag1", "tag2"], "topic": "my-topic", "url": "https://example.com/webhook" } ``` ``` -------------------------------- ### Create URL Group with Endpoints Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Use this to create a new URL group and add initial endpoints. Ensure you have your QStash token. ```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 Queues Source: https://upstash.com/docs/qstash/api-reference/queues/list-queues Lists all available queues in your QStash account. ```APIDOC ## GET /v2/queues ### Description List all your queues ### Method GET ### Endpoint /v2/queues ### Parameters #### Query Parameters - **qstash_token** (string) - Required - QStash authentication token passed as a query parameter ### Request Example (No request body for GET request) ### 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 #### Response Example ```json [ { "name": "my-queue", "createdAt": 1678886400000, "updatedAt": 1678886400000, "parallelism": 10, "paused": false, "lag": 0 } ] ``` ``` -------------------------------- ### QStash Dev Server User 3 Credentials Source: https://upstash.com/docs/qstash/howto/local-development Environment variables for User 3 to connect to the QStash development server. Use these for testing. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjIiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_6jWGaWRxHsw4vMSPJprXadyvrybF" QSTASH_NEXT_SIGNING_KEY="sig_7qHbvhmahe5GwfePDiS5Lg3pi6Qx" ``` -------------------------------- ### Configure QStash Client with Custom Retries Source: https://upstash.com/docs/qstash/sdks/py/gettingstarted Initialize the QStash client with custom retry settings, including the number of retries and a specific backoff function. This configuration applies to the client's request retries, not QStash's internal retry policies. ```python from qstash import QStash client = QStash( "", retry={ "retries": 3, "backoff": lambda retry_count: (2**retry_count) * 20, }, ) ``` -------------------------------- ### QStash Dev Server User 4 Credentials Source: https://upstash.com/docs/qstash/howto/local-development Environment variables for User 4 to connect to the QStash development server. Use these for testing. ```javascript QSTASH_URL="http://localhost:8080" QSTASH_TOKEN="eyJVc2VySUQiOiJ0ZXN0VXNlcjMiLCJQYXNzd29yZCI6InRlc3RQYXNzd29yZCJ9" QSTASH_CURRENT_SIGNING_KEY="sig_5T8FcSsynBjn9mMLBsXhpacRovJf" QSTASH_NEXT_SIGNING_KEY="sig_7GFR4YaDshFcqsxWRZpRB161jguD" ``` -------------------------------- ### Initialize Receiver with Cloudflare Secrets Store Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Configure the QStash Receiver by retrieving signing keys from the Cloudflare Secrets Store via the environment object. ```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 }, }; ``` -------------------------------- ### Publishing a Background Job with QStash 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 URL Group with Endpoints Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Use this to create a new URL group and add initial endpoints. Ensure you have your QStash token configured. ```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" }, ], }); ``` -------------------------------- ### QStash Environment Variables for Next.js Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Configure your QStash credentials by setting these environment variables in your .env file. Ensure all three values are copied from your QStash dashboard. ```bash # Copy all three from your QStash dashboard QSTASH_TOKEN= QSTASH_CURRENT_SIGNING_KEY= QSTASH_NEXT_SIGNING_KEY= ``` -------------------------------- ### Implement Server Action for QStash Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs A server action that uses the QStash client to publish a JSON payload to a target URL. ```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", }, }) } ``` -------------------------------- ### Create Initial UI Component Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs A basic client-side component with a button to trigger background jobs. ```tsx "use client" export default function Home() { return (
) } ``` -------------------------------- ### Configure Migration Mode Source: https://upstash.com/docs/qstash/howto/multi-region Set the QSTASH_REGION and region-specific credentials to enable simultaneous multi-region support. This mode requires access to process.env and is not compatible with environments like Cloudflare Workers. ```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" ``` -------------------------------- ### Create a schedule with callbacks Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Configures a schedule to trigger a callback URL upon success or failure. ```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...", ) ``` -------------------------------- ### Publish Webhook URL with QStash Source: https://upstash.com/docs/qstash/howto/webhook Use this format when configuring your webhook URL as a QStash publish request. Custom retries, timeouts, and other settings can be specified using HTTP headers or query parameters. ```bash https://qstash.upstash.io/v2/publish/https://example.com/api/webhook?qstash_token= ``` -------------------------------- ### Fetch Paginated DLQ Messages with Cursor Source: https://upstash.com/docs/qstash/sdks/py/examples/dlq Retrieve all messages from the DLQ, handling pagination with a cursor. Initialize the QStash client with your token. The loop continues fetching messages and updating the cursor until no more messages are available. ```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 ``` -------------------------------- ### POST /docs/_mintlify/feedback/upstash/agent-feedback Source: https://upstash.com/docs/qstash/api-reference/messages/cancel-a-message Submit feedback regarding documentation issues. ```APIDOC ## POST /docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback if you encounter incorrect, outdated, or confusing documentation. ### Method POST ### Request Body - **path** (string) - Required - The current page path. - **feedback** (string) - Required - Description of the issue. ### Request Example { "path": "/current-page-path", "feedback": "Description of the issue" } ``` -------------------------------- ### Verify Signature with QStash SDK (Python) Source: https://upstash.com/docs/qstash/howto/signature Utilize the Receiver class from the qstash Python library for signature verification. Provide your signing keys and site URL to the Receiver constructor. ```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", ) ``` -------------------------------- ### Authenticate QStash API with Query Parameter Source: https://upstash.com/docs/qstash/api/authentication Use the qstash_token query parameter when setting request headers is not possible. ```bash curl https://qstash.upstash.io/v2/publish/...?qstash_token= ``` -------------------------------- ### Deploy CDK Stack Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Executes the deployment of the defined infrastructure to AWS. ```bash cdk deploy ``` -------------------------------- ### Setting Parallelism Limit Source: https://upstash.com/docs/qstash/features/flowcontrol Demonstrates how to set a parallelism limit for message delivery using the QStash client and cURL. ```APIDOC ## Setting Parallelism Limit This section shows how to configure the maximum number of concurrent messages that can be active for a given flow control key. ### TypeScript Example ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", parallelism: 10 }, }); ``` ### cURL Example ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:parallelism=10" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` ``` -------------------------------- ### Reset Rate Count Source: https://upstash.com/docs/qstash/features/flowcontrol Reset the rate count and end the current rate period for a flow control key, allowing the next message to start a fresh rate period. ```APIDOC ## Reset Rate Count ### Description Resets the rate count and ends the current rate period for a flow control key. The next message delivery will start a fresh rate period. ### Method POST ### Endpoint `/v2/flowControl/{key}/resetRate` ### Path Parameters - **key** (string) - Required - The flow control key whose rate count needs to be reset. ### Request Example ```bash curl -X POST https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/resetRate \ -H "Authorization: Bearer " ``` ### Request Example (TypeScript) ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.flowControl.resetRate("USER_GIVEN_KEY"); ``` ``` -------------------------------- ### Combining Rate, Parallelism, and Period Source: https://upstash.com/docs/qstash/features/flowcontrol Illustrates how to set rate limits, parallelism, and the time period together for advanced flow control. ```APIDOC ## Rate, Parallelism, and Period Together This section explains how to combine rate limiting, parallelism, and a defined period for granular control over message delivery. ### TypeScript Example ```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" }, }); ``` ### cURL Example ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:rate=10,parallelism=20,period=1m" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` ``` -------------------------------- ### List Schedules Source: https://upstash.com/docs/qstash/api-reference/schedules/list-schedules Retrieves a list of all schedules configured in QStash. ```APIDOC ## GET /v2/schedules ### Description List all schedules. ### Method GET ### Endpoint /v2/schedules ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of schedules to return. - **offset** (integer) - Optional - The number of schedules to skip before returning results. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **schedules** (array) - An array of Schedule objects. - **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. - **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. - **isPaused** (boolean) - Whether the schedule is paused. - **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. - **label** (string) - The label 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. - **lastScheduleStates** (object) - The states of the last scheduled messages. #### Response Example ```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 Message to QStash Source: https://upstash.com/docs/qstash/quickstarts/fly-io/go Send a POST request to the QStash API to trigger the webhook on the deployed application. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/https://winter-cherry-9545.fly.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Publish a Message with cURL Source: https://upstash.com/docs/qstash/overall/getstarted Use this cURL command to publish a JSON message to a specified API endpoint. Ensure you replace `` with your actual token and `` with your target URL. The `Content-type` header should match the body's format. ```bash curl -XPOST \ -H 'Authorization: Bearer ' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://' ``` -------------------------------- ### Publishing a Message to QStash Source: https://upstash.com/docs/qstash/quickstarts/deno-deploy This curl command demonstrates how to publish a JSON message to a Deno deploy endpoint via QStash. Replace the placeholder URL and token with your actual values. ```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\"}" ``` -------------------------------- ### List All Schedules with cURL Source: https://upstash.com/docs/qstash/overall/apiexamples List all schedules using cURL. Include your authorization token in the header. ```shell curl https://qstash.upstash.io/v2/schedules \ -H "Authorization: Bearer XXX" ``` -------------------------------- ### Publish Message to QStash Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Sends a POST request to QStash to trigger the deployed Lambda function. ```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\"}" ``` -------------------------------- ### Create URL Group and Endpoints using Python Source: https://upstash.com/docs/qstash/howto/url-group-endpoint This Python code uses the QStash library to add endpoints to a URL Group. Ensure you provide your QStash token and the correct URL group name. ```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"}, ], ) ``` -------------------------------- ### Publish with Flow Control (TypeScript) Source: https://upstash.com/docs/qstash/features/flowcontrol Use this to publish a JSON message with flow control limits including parallelism, rate, and period. Requires a QStash client initialized with your token. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", parallelism: 5, rate: 10, period: "1m" }, }); ``` -------------------------------- ### POST /_mintlify/feedback/upstash/agent-feedback Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Submits feedback regarding documentation issues. ```APIDOC ## POST /_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback for incorrect or outdated documentation. ### Request Body - **path** (string) - Required - The current page path. - **feedback** (string) - Required - Description of the issue. ``` -------------------------------- ### Create URL Group and Endpoints using cURL Source: https://upstash.com/docs/qstash/howto/url-group-endpoint Use this cURL command to create a URL Group and add endpoints to it via the REST API. Ensure you replace `` with your actual QStash token. ```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" } ] }' ``` -------------------------------- ### Update UI with Server Action Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs The updated Home 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 (
) } ``` -------------------------------- ### Configure Queue Parallelism with Python Source: https://upstash.com/docs/qstash/features/queues Configure queue parallelism using the QStash Python client. This method allows you to set the desired concurrency level for message processing. ```python from qstash import QStash client = QStash("") client.queue.upsert("my-queue", parallelism=5) ``` -------------------------------- ### Verify Signature with QStash SDK (TypeScript) Source: https://upstash.com/docs/qstash/howto/signature Use the Receiver type from the QStash SDK to verify incoming request signatures. Ensure you provide your current and next signing keys, and the URL of your site. ```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", }); ``` -------------------------------- ### Publish Image Processing Task with QStash Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Use this endpoint to queue an image processing task after an image has been uploaded. Ensure your QSTASH_TOKEN is set in your environment variables. ```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, }) } ``` -------------------------------- ### Callback and Redaction Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Overview of headers used to manage callback configurations, failure callbacks, and data redaction settings. ```APIDOC ## Callback and Redaction Headers ### Description These headers are used to configure how QStash handles callbacks, failure notifications, and sensitive data redaction. ### Parameters #### Request Headers - **Upstash-Callback-Forward-*** (string) - Optional - Custom headers to be forwarded to the callback URL. Prefix with `Upstash-Callback-Forward-` to have the prefix stripped before forwarding. - **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** (integer) - Optional - Number of retries for the callback request. - **Upstash-Callback-Retry-Delay** (string) - Optional - Delay between retries for the callback request. - **Upstash-Failure-Callback** (string) - Optional - URL to be called when all delivery retries are exhausted. - **Upstash-Failure-Callback-Forward-*** (string) - Optional - Custom headers to be forwarded to the failure callback URL. Prefix with `Upstash-Failure-Callback-Forward-` to have the prefix stripped. - **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 request. - **Upstash-Failure-Callback-Retries** (integer) - Optional - Number of retries for the failure callback request. - **Upstash-Failure-Callback-Retry-Delay** (string) - Optional - Delay between retries for the failure callback request. - **Upstash-Redact-Fields** (string) - Optional - Comma-separated list of fields to redact (e.g., `body`). Redacted fields appear as `REDACTED:` in logs and responses. ``` -------------------------------- ### Publish Message to Endpoint using Python SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message to a specific endpoint using the QStash Python SDK. Replace '' with your token. An async version is also available. ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, ) # Async version is also available ``` -------------------------------- ### Create a schedule to a URL group Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Targets a pre-defined URL group instead of a single endpoint. ```python from qstash import QStash client = QStash("") client.schedule.create( destination="my-url-group", cron="0 * * * *", ) ``` -------------------------------- ### Configure Single-Region Mode Source: https://upstash.com/docs/qstash/howto/multi-region Set these environment variables to operate in single-region mode using the EU endpoint. ```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" ``` -------------------------------- ### Create Periodic Data Fetching API Route Source: https://upstash.com/docs/qstash/recipes/periodic-data-updates Implement a Next.js API route that fetches data from an external API and stores it in Redis, protected by QStash 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, }, }; ``` -------------------------------- ### Publish Job to QStash (Next.js Actions) Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Server-side action in a Next.js application that uses the QStash client to publish a JSON message. Ensure the QSTASH_TOKEN environment variable is set. ```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; } } ``` -------------------------------- ### Configure Queue Parallelism with TypeScript Source: https://upstash.com/docs/qstash/features/queues Use the QStash client library in TypeScript to configure the parallelism for a specific queue. This allows for controlled message processing. ```typescript const client = new Client({ token: "" }); const queue = client.queue({ queueName: "my-queue" }) await queue.upsert({ parallelism: 1, }) ``` -------------------------------- ### Publish a Message to RequestCatcher with cURL Source: https://upstash.com/docs/qstash/overall/getstarted This cURL command demonstrates publishing a message to a RequestCatcher URL for testing purposes. Replace `` with your token. This is useful for verifying message delivery and content. ```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' ``` -------------------------------- ### Retrieve Signing Keys Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Fetches the current and next signing keys. ```APIDOC ## GET /v1/signing-key ### Description Retrieves the current and next signing keys for your QStash account. ### Method GET ### Endpoint /v1/signing-key ### Request Example ```python from qstash import QStash client = QStash("") signing_key = client.signing_key.get() print(signing_key.current, signing_key.next) ``` ### Response #### Success Response (200) - **current** (string) - The current signing key. - **next** (string) - The next signing key. #### Response Example ```json { "current": "your_current_signing_key", "next": "your_next_signing_key" } ``` ``` -------------------------------- ### Python HTTP Server for Public Endpoint Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Create a simple HTTP server using Python's http.server module to expose the cleanup logic as a public endpoint. This handler processes POST requests to trigger the database cleanup. ```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() ``` -------------------------------- ### POST /v2/queues Source: https://upstash.com/docs/qstash/api-reference/queues/upsert-a-queue Updates or creates a queue in QStash. Note that parallelism greater than 1 is planned for deprecation in favor of Flow Control. ```APIDOC ## POST /v2/queues ### Description Updates or creates a queue. Queues with parallelism set to 1 provide FIFO guarantees. ### 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 (default: 1) ### Request Example { "queueName": "my-queue", "parallelism": 1 } ### Response #### Success Response (200) - **description** (string) - Queue created or updated successfully #### Error Response (400) - **error** (string) - Queue name is invalid. Queue names can only contain alphanumeric characters, hyphens, periods, and underscores. #### Error Response (412) - **error** (string) - Either exceeded the maximum number of queues allowed or the maximum parallelism per queue. ``` -------------------------------- ### Publish Message with Delay using Python SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message with a delay using the QStash Python SDK. The 'delay' parameter accepts a string like '5m'. Replace '' with your token. An async version is also available. ```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 ``` -------------------------------- ### Send a custom header with QStash Source: https://upstash.com/docs/qstash/overall/apiexamples Include custom headers in published messages to pass metadata to the destination endpoint. ```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 const client = new Client({ token: "" }); 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://example.com", body={ "hello": "world", }, headers={ "My-Header": "my-value", }, ) # Async version is also available ``` -------------------------------- ### Publish Message to URL Group using Python SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message to a URL Group using the QStash Python SDK. Replace '' with your token. An async version is also available. ```python from qstash import QStash client = QStash("") client.message.publish_json( url_group="my-url-group", body={ "hello": "world", }, ) # Async version is also available ``` -------------------------------- ### Pin Flow Control Configuration Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Set a fixed configuration for parallelism and rate limits for a flow control key, preventing incoming messages from overriding these settings. Specify the desired `parallelism`, `rate`, and `period` in seconds. Requires an initialized QStash client. ```python from qstash import QStash client = QStash("") # Pin parallelism and rate so incoming messages cannot override them client.flow_control.pin( "USER_GIVEN_KEY", {"parallelism": 3, "rate": 20, "period": 120}, ) info = client.flow_control.get("USER_GIVEN_KEY") print(info.is_pinned_parallelism) # True print(info.is_pinned_rate) # True ``` -------------------------------- ### QStash Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule A collection of headers used to control message delivery, retry strategies, and callback behavior. ```APIDOC ## Request Headers ### Upstash-Retry-Delay - **Description**: Customize the delay between retry attempts when message delivery fails. Uses mathematical expressions with the `retried` variable. - **Type**: string ### Upstash-Delay - **Description**: Delay the message delivery. Format is `` (e.g., 50s, 1d10m). - **Type**: string ### Upstash-Forward-* - **Description**: Send custom headers to your endpoint. Prefix the header name with `Upstash-Forward-` to have the prefix stripped before delivery. - **Type**: string ### Upstash-Callback - **Description**: Define a callback URL called after each attempt. Must be prefixed with http:// or https://. - **Type**: string ### Upstash-Callback-Forward-* - **Description**: Send custom headers along with your callback message. Prefix with `Upstash-Callback-Forward-`. - **Type**: string ### Upstash-Callback-* - **Description**: Customize callback configuration including `Upstash-Callback-Method`, `Upstash-Callback-Timeout`, `Upstash-Callback-Retries`, and `Upstash-Callback-Retry-Delay`. - **Type**: string ### Upstash-Failure-Callback - **Description**: Define a failure callback URL called when all defined retries are exhausted. - **Type**: string ``` -------------------------------- ### QStash Message Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Overview of headers used to control message delivery, retries, deduplication, and callback behavior. ```APIDOC ## Message Configuration Headers ### Description These headers are used to configure how messages are handled, retried, and tracked within the QStash system. ### Parameters #### Request Headers - **Upstash-Retry-Count** (string) - Optional - Number of times to retry the message. Defaults: 3 (Free), 5 (Paid). - **Upstash-Retry-Delay** (string) - Optional - Mathematical expression to compute delay between retries (e.g., '1000', 'pow(2, retried) * 1000'). - **Upstash-Label** (string) - Optional - Label for identification and filtering in logs and DLQ. - **Upstash-Deduplication-Id** (string) - Optional - ID for de-duplicating messages within a 10-minute window. - **Upstash-Content-Based-Deduplication** (string) - Optional - 'true' or 'false'. If true, hashes message body for deduplication. - **Upstash-Callback** (string) - Optional - URL to receive a callback after message delivery (success or failure). - **Upstash-Callback-Forward-* ** (string) - Optional - Custom headers to forward to the callback destination. - **Upstash-Callback-Method** (string) - Optional - HTTP method to use for the callback request. ``` -------------------------------- ### Retrieve a Message using QStash Source: https://upstash.com/docs/qstash/sdks/py/examples/messages Use this snippet to fetch a specific message from QStash using its ID. Ensure you have initialized the QStash client with your token. ```python from qstash import QStash client = QStash("") msg = client.message.get("") ``` -------------------------------- ### Rotate QStash Signing Keys 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) ``` -------------------------------- ### Callback configuration headers Source: https://upstash.com/docs/qstash/features/callbacks Headers used to configure callback behavior such as timeout, retries, and delays. ```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 ``` -------------------------------- ### Execute background job logic Source: https://upstash.com/docs/qstash/features/background-jobs This public API endpoint in Next.js contains the logic for the background job, such as sending emails to a list of users. It is invoked by QStash. ```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 }); } ``` -------------------------------- ### Publish with Flow Control (cURL) Source: https://upstash.com/docs/qstash/features/flowcontrol Use this to publish a message with flow control limits including parallelism, rate, and period via cURL. Ensure to replace XXX with your actual token. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:parallelism=5,rate=10,period=1m" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` -------------------------------- ### Publishing a Message with a Callback Source: https://upstash.com/docs/qstash/features/callbacks Configure a callback URL when publishing a message to receive delivery status updates. ```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...", ) ``` -------------------------------- ### Delete a Queue Source: https://upstash.com/docs/qstash/sdks/py/examples/queues This code demonstrates how to delete a queue from Qstash. Ensure that no critical operations are running when deleting a queue, as changes can take up to a minute to fully propagate. ```python from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.delete(queue_name) ``` -------------------------------- ### Publish Message to QStash via cURL Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Send a POST request to the QStash endpoint to trigger the worker. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/https://..workers.dev" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Create a Queue with Parallelism Source: https://upstash.com/docs/qstash/sdks/py/examples/queues Use this snippet to create a new queue or update an existing one with a specified parallelism level. The `upsert` method is used for this operation. ```python from qstash import QStash client = QStash("") queue_name = "upstash-queue" client.queue.upsert(queue_name, parallelism=2) print(client.queue.get(queue_name)) ``` -------------------------------- ### Forwarding custom 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 ``` -------------------------------- ### POST /v2/enqueue/{queueName}/{destination} Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Enqueue a message to a specified queue. The queue will be created if it does not exist. The destination can be a URL or a URL Group. ```APIDOC ## POST /v2/enqueue/{queueName}/{destination} ### Description Enqueue a message to the specified queue. ### Method POST ### Endpoint /v2/enqueue/{queueName}/{destination} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to enqueue the message to. If it doesn't exist, it will be created automatically with default parallelism. - **destination** (string) - Required - 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. Note that destination must be publicly accessible over the internet. #### Header Parameters - **Content-Type** (string) - Optional - The MIME type of the message. Recommended to set for proper content interpretation by the destination API. Examples: `application/json`, `text/plain`. - **Upstash-Forward-** (string) - Optional - Custom headers to send to the destination. The `Upstash-Forward-` prefix will be stripped. - **Upstash-Method** (string) - Optional - The HTTP method to use when sending the request to your API. Defaults to POST. Allowed values: GET, POST, PUT, PATCH, DELETE. - **Upstash-Timeout** (string) - Optional - Specifies the maximum duration the request is allowed to take before timing out. Format: `` where unit is `s`, `m`, or `h`. Example: `5s`, `2m`. - **Upstash-Retries** (integer) - Optional - The number of times to retry the message if it fails. ### Request Example ```json { "body": "This is the message body." } ``` ### Response #### Success Response (200) - **messageId** (string) - The ID of the enqueued message. #### Response Example ```json { "messageId": "msg_abc123" } ``` ``` -------------------------------- ### List All URL Groups Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Fetch a list of all existing URL groups. This is useful for an overview of your routing configurations. ```python from qstash import QStash client = QStash("") all_url_groups = client.url_group.list() for url_group in all_url_groups: print(url_group.name, url_group.endpoints) ``` -------------------------------- ### Create a schedule with callbacks Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Defines a schedule that triggers a callback URL upon completion or failure. ```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...", }); ``` -------------------------------- ### Build and Zip Script for Lambda Deployment Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Add this script to your package.json to build and zip your Node.js code for AWS Lambda deployment. It uses esbuild for bundling and minification, and then zips the output. ```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*" } } ``` -------------------------------- ### Test QStash Integration with cURL Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Use this cURL command to send a POST request to your deployed Lambda function's URL via QStash. Ensure you replace placeholders with your actual Lambda URL and QStash token. ```bash curl --request POST "https://qstash.upstash.io/v2/publish/" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d "{ \"hello\": \"world\"}" ``` -------------------------------- ### Batching messages with headers and body Source: https://upstash.com/docs/qstash/features/batch Include custom headers and request bodies for each message within a batch. ```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"}, }, ] ) ``` -------------------------------- ### Submit Documentation Feedback Source: https://upstash.com/docs/qstash/api-reference/url-groups/upsert-url-group-and-endpoint Instructions for submitting feedback regarding documentation issues. ```APIDOC ## POST https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback if you encounter incorrect, outdated, or confusing documentation. ### Request Body - **path** (string) - Required - The current page path. - **feedback** (string) - Required - Description of the issue. ``` -------------------------------- ### 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, }, }); ``` -------------------------------- ### Import QStash Receiver Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Import the Receiver class from the @upstash/qstash library. This class is used for validating incoming QStash webhook signatures. ```typescript import { Receiver } from "@upstash/qstash"; ``` -------------------------------- ### POST /v2/schedules/{destination} Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule Create a schedule to send messages periodically. The destination can be a URL or a URL Group name. ```APIDOC ## POST /v2/schedules/{destination} ### Description Create a schedule to send messages periodically. ### Method POST ### Endpoint /v2/schedules/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - 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. #### Header Parameters - **Upstash-Cron** (string) - Required - 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. Examples: `*/5 * * * *`, `CRON_TZ=America/New_York */5 * * * *` - **Upstash-Schedule-Id** (string) - Optional - 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. - **Content-Type** (string) - Optional - MIME type of the message. Recommended to help your destination API understand the content. Examples: `application/json`, `application/xml`, `application/octet-stream`, `text/plain` - **Upstash-Method** (string) - Optional - The HTTP method to use when sending the request to your API. Enum: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`. Default: `POST` - **Upstash-Timeout** (string) - Optional - Specifies the maximum duration the request is allowed to take before timing out. Format: `` where unit is `s` (seconds), `m` (minutes), or `h` (hours). Examples: `5s`, `2m`, `1h` - **Upstash-Retries** (integer) - Optional - How many times should this message be retried in case the destination API returns an error or is not available. The total number of deliveries is 1 (initial attempt) + retries. If not provided, the plan default retry value will be used (Free Plan: 3 retries, Paid Plans: 5 retries). - **Upstash-Retry-Delay** (string) - Optional - Specifies the delay between retries. Format: `` where unit is `s` (seconds), `m` (minutes), or `h` (hours). Example: `10s` ### Request Body (Not specified in the provided OpenAPI schema) ### Request Example (Not specified in the provided OpenAPI schema) ### Response #### Success Response (200) (Not specified in the provided OpenAPI schema) #### Response Example (Not specified in the provided OpenAPI schema) ``` -------------------------------- ### Create a Schedule with Redacted Fields Source: https://upstash.com/docs/qstash/howto/redact-fields Use this to create a new schedule that automatically redacts specified fields in the message body and headers for all produced messages. Ensure you have the QStash client initialized with your token. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.schedule.create({ name: "my-schedule", cron: "0 * * * *", url: "https://my-api...", body: { hello: "world" }, redact: { body: true, header: ["Authorization"] }, }); ``` ```python from qstash import QStash client = QStash("") client.schedule.create( name="my-schedule", cron="0 * * * *", url="https://my-api...", body={"hello": "world"}, redact={ "body": True, "header": ["Authorization"] }, ) ``` ```curl curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -H "Upstash-Redact-Fields: body, header[Authorization]" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ``` -------------------------------- ### Authenticate QStash API with Bearer Token Source: https://upstash.com/docs/qstash/api/authentication Use the Authorization header to pass your QSTASH_TOKEN. This is the standard method for authenticating requests. ```bash curl https://qstash.upstash.io/v2/publish/... \ -H "Authorization: Bearer " ``` -------------------------------- ### Batch Anthropic LLM Requests with QStash Source: https://upstash.com/docs/qstash/integrations/anthropic Send multiple LLM requests to Anthropic concurrently using `client.batchJSON`. Each request in the batch should specify the Anthropic provider and a unique callback URL for handling responses. ```typescript import { anthropic, Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const result = await client.batchJSON([ { api: { name: "llm", provider: anthropic({ token: "" }) }, body: { model: "claude-3-5-sonnet-20241022", messages: [ { role: "user", content: "Describe the latest in AI research.", }, ], }, callback: "https://example.com/callback1", }, { api: { name: "llm", provider: anthropic({ token: "" }) }, body: { model: "claude-3-5-sonnet-20241022", messages: [ { role: "user", content: "Outline the future of remote work.", }, ], }, callback: "https://example.com/callback2", }, // Add more requests as needed ]); console.log(result); ``` -------------------------------- ### Implement QStash Webhook Verification in Lambda Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs This TypeScript code demonstrates how to verify incoming webhook signatures using the Upstash QStash SDK within an AWS Lambda function. Ensure QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY environment variables are set during deployment. ```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" }), } } ``` -------------------------------- ### Publish with Rate and Period Limits (cURL) Source: https://upstash.com/docs/qstash/features/flowcontrol Use this to publish a message with rate and period limits via cURL. Ensure to replace XXX with your actual token. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:rate=10,period=1m" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` -------------------------------- ### Update QStash SDK dependency Source: https://upstash.com/docs/qstash/howto/multi-region Ensure the SDK is updated to version 2.9.0 or higher to support migration mode. ```bash npm install @upstash/qstash@latest ``` -------------------------------- ### POST /v2/topics/:urlGroupName/endpoints Source: https://upstash.com/docs/qstash/howto/url-group-endpoint Create a URL Group and add endpoints to it using the QStash REST API. ```APIDOC ## POST /v2/topics/:urlGroupName/endpoints ### Description Creates a URL Group and adds specified endpoints to it. If the URL Group does not exist, it will be created. ### Method POST ### Endpoint `/v2/topics/:urlGroupName/endpoints` ### Parameters #### Path Parameters - **urlGroupName** (string) - Required - The name of the URL Group. #### Request Body - **endpoints** (array) - Required - A list of endpoints to add to the URL Group. - **name** (string) - Required - The name of the endpoint. - **url** (string) - Required - The URL of the endpoint. ### Request Example ```json { "endpoints": [ { "name": "endpoint1", "url": "https://example.com" }, { "name": "endpoint2", "url": "https://somewhere-else.com" } ] } ``` ### Response #### Success Response (200) This endpoint does not explicitly define a success response body in the documentation. Typically, a 200 OK status indicates the request was processed successfully. #### Error Response - **400 Bad Request**: If the request body is invalid or missing required fields. - **401 Unauthorized**: If the authentication token is invalid or missing. - **404 Not Found**: If the specified URL Group or resource is not found (though this endpoint is designed to create them). - **500 Internal Server Error**: If there is a server-side issue. ``` -------------------------------- ### Create URL Group and Endpoints using TypeScript Source: https://upstash.com/docs/qstash/howto/url-group-endpoint This TypeScript code snippet demonstrates how to add endpoints to a URL Group using the Upstash QStash client. Replace `` with your actual token. ```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" }, ], }); ``` -------------------------------- ### List All Schedules Source: https://upstash.com/docs/qstash/howto/delete-schedule Retrieve a list of all your schedules if you do not know the specific schedule ID. This is useful for managing or identifying schedules before deletion. ```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() ``` -------------------------------- ### List all schedules Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Retrieves a list of all schedules associated with the client. ```python from qstash import QStash client = QStash("") all_schedules = client.schedule.list() print(all_schedules) ``` -------------------------------- ### Publish Message to Endpoint using Typescript SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message to a specific endpoint using the QStash Typescript SDK. Replace '' with your token. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, }); ``` -------------------------------- ### QStash Message Configuration Headers Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Headers used to customize message delivery, retry logic, and flow control. ```APIDOC ## Message Configuration Headers ### Description These headers are used to configure message delivery behavior, including delays, deduplication, and flow control. ### Parameters #### Request Headers - **Upstash-Delay** (string) - Optional - Delay the message delivery. Format: `` (s, m, h, d). - **Upstash-Not-Before** (integer) - Optional - Delay delivery until a specific Unix timestamp (UTC). - **Upstash-Label** (string) - Optional - Label for identification and filtering in logs/DLQ. - **Upstash-Flow-Control-Key** (string) - Optional - Key for rate limiting messages. - **Upstash-Flow-Control-Value** (string) - Optional - Defines parallelism, rate, and period for flow control. Format: `parallelism=, rate=, period=`. - **Upstash-Deduplication-Id** (string) - Optional - ID for de-duplicating messages within a 10-minute window. - **Upstash-Content-Based-Deduplication** (string) - Optional - Enable content-based hashing for deduplication. Values: 'true', 'false'. - **Upstash-Callback** (string) - Optional - URL to be called after message delivery (success or failure). ``` -------------------------------- ### Authentication Schemes Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Details on how to authenticate requests using Bearer tokens or query parameters. ```APIDOC ## Authentication ### Description QStash supports two methods for authentication using a JWT token. ### Security Schemes - **bearerAuth** (http) - Bearer token authentication using the Authorization header. - **bearerAuthQuery** (apiKey) - Token authentication passed via the `qstash_token` query parameter. ``` -------------------------------- ### Handle Burst Rate Limit Error in TypeScript Source: https://upstash.com/docs/qstash/api/api-ratelimiting This code demonstrates how to handle `QstashRatelimitError` for burst rate limits. It logs the reset time and advises implementing exponential backoff or delays before retrying. ```typescript import { QstashRatelimitError } from "@upstash/qstash"; try { // Example of a request that could hit the burst 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 QstashRatelimitError) { console.log("Burst rate limit exceeded. Retry after:", error.reset); // Implement exponential backoff or delay before retrying } else { console.error("An unexpected error occurred:", error); } } ``` -------------------------------- ### Securing API Routes with Signature Verification Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Uses verifySignatureAppRouter to ensure requests originate from QStash by validating signing keys. ```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) ``` -------------------------------- ### Enqueue Message to a Queue Source: https://upstash.com/docs/qstash/features/queues Send a message to a specific queue for processing. Ensure the queue is configured with appropriate parallelism to handle the incoming messages. ```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!"}' ``` -------------------------------- ### Enable Content-Based Deduplication using cURL Source: https://upstash.com/docs/qstash/features/deduplication Set the `Upstash-Content-Based-Deduplication` header to `true` to have QStash automatically generate a deduplication ID based on the message's destination, body, and specific headers. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Content-Based-Deduplication: true" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/...' ``` -------------------------------- ### Send a single email with Resend Source: https://upstash.com/docs/qstash/integrations/resend Uses the publishJSON method to send a single email. Requires QSTASH_TOKEN and RESEND_TOKEN environment variables. ```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!

", }, }); ``` -------------------------------- ### 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) ``` -------------------------------- ### Receive and Verify QStash Message in Next.js Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs This endpoint receives QStash messages and verifies their signature using `verifySignatureAppRouter`. It processes the image based on the provided `imageId`. ```tsx import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" // 👇 Verify that this messages comes from QStash export const POST = verifySignatureAppRouter(async (req: Request) => { const body = await req.json() const { imageId } = body as { imageId: string } // Image processing logic, i.e. using sharp return new Response(`Image with id "${imageId}" processed successfully.`) }) ``` -------------------------------- ### Submitting Feedback Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-global-parallelism Instructions for submitting feedback on documentation issues. ```APIDOC ## POST https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback if you encounter incorrect, outdated, or confusing documentation. Only submit feedback when you have something specific and actionable to report. ### Request Body - **path** (string) - Required - The current page path - **feedback** (string) - Required - Description of the issue ### Request Example { "path": "/v2/globalParallelism", "feedback": "The response example is missing a field." } ``` -------------------------------- ### Fetch All DLQ Messages with Pagination Source: https://upstash.com/docs/qstash/sdks/ts/examples/dlq Iterate through all DLQ messages using a cursor for pagination. This is useful when the DLQ contains a large number of messages. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const all_messages = []; let cursor = null; while (true) { const res = await client.dlq.listMessages({ cursor }); all_messages.push(...res.messages); cursor = res.cursor; if (!cursor) { break; } } ``` -------------------------------- ### Publish Message to URL Group using Typescript SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message to a URL Group using the QStash Typescript SDK. Replace '' with your token. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ urlGroup: "myUrlGroup", body: { hello: "world", }, }); ``` -------------------------------- ### Enable Content-Based Deduplication using Python Source: https://upstash.com/docs/qstash/features/deduplication The Python QStash client supports content-based deduplication via the `content_based_deduplication` argument in the `publish_json` method. This automatically generates a deduplication ID. ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, content_based_deduplication=True, ) ``` -------------------------------- ### Enqueue Message to a Queue with Python Source: https://upstash.com/docs/qstash/features/queues Send a JSON message to a QStash queue using the Python client. This function is useful for asynchronous task processing. ```python from qstash import QStash client = QStash("") client.message.enqueue_json( queue="my-queue", url="https://example.com", body={ "Hello": "World", }, ) ``` -------------------------------- ### Unpin Flow Control Configuration Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Remove pinned configurations for parallelism and/or rate limits for a flow control key, allowing incoming messages to influence these settings again. You can unpin them independently by specifying `"parallelism": True` or `"rate": True`. Requires an initialized QStash client. ```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}, ) ``` -------------------------------- ### Publish Message with Delay using Typescript SDK Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message with a delay using the QStash Typescript SDK. The 'delay' option accepts seconds. Replace '' with your token. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world", }, delay: 300, }); ``` -------------------------------- ### Create a Schedule Source: https://upstash.com/docs/qstash/features/schedules Create a schedule to publish a message periodically using a cron expression. ```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' ``` -------------------------------- ### Schedule messages with cron Source: https://upstash.com/docs/qstash/overall/apiexamples Configure messages to run on a recurring schedule using cron syntax. ```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 ``` -------------------------------- ### Schedule to a URL Group Source: https://upstash.com/docs/qstash/features/schedules Create a schedule that targets a URL group by name or ID. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "urlGroupName", cron: "* * * * *", }); ``` ```python from qstash import QStash client = QStash("") client.schedule.create( destination="url-group-name", cron="* * * * *", ) ``` ```bash curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/' ``` -------------------------------- ### Publish with Deduplication ID using Python Source: https://upstash.com/docs/qstash/features/deduplication The Python QStash client enables deduplication by providing the `deduplication_id` argument to the `publish_json` method. This ensures that the corresponding header is sent with the request. ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, deduplication_id="abcdef", ) ``` -------------------------------- ### Handle Background Task (Next.js API Route) Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs An API route in a Next.js application designed to handle background tasks received from QStash. It processes the incoming JSON data and forwards it to a specified endpoint, retrying up to 10 times with a 500ms delay between attempts. It uses `verifySignatureAppRouter` for secure verification. ```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) ``` -------------------------------- ### Retrieve a message with TypeScript Source: https://upstash.com/docs/qstash/sdks/ts/examples/messages Fetches a specific message by its ID using the QStash client. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const messages = client.messages const msg = await messages.get("msgId"); ``` -------------------------------- ### POST /v2/publish/{url} (Absolute Delay) Source: https://upstash.com/docs/qstash/features/delay Publishes a message with an absolute delay using the Upstash-Not-Before header. ```APIDOC ## POST /v2/publish/{url} ### Description Delays a message until a specific future time defined by a Unix timestamp. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Request Headers - **Upstash-Not-Before** (integer) - Optional - Unix timestamp in seconds (UTC). ### Request Example curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Not-Before: 1657104947" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ``` -------------------------------- ### Handle Daily Rate Limit Error in TypeScript Source: https://upstash.com/docs/qstash/api/api-ratelimiting Use this snippet to catch and handle `QstashDailyRatelimitError` when a daily rate limit is exceeded. It logs the reset time and suggests implementing retry logic or user notification. ```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); } } ``` -------------------------------- ### Enqueue Message to a Queue with TypeScript Source: https://upstash.com/docs/qstash/features/queues Use the QStash TypeScript client to enqueue a JSON message to a specified queue. This is a common way to send data for asynchronous processing. ```typescript const client = new Client({ token: "" }); const queue = QStashClient.queue({ queueName: "my-queue" }) await queue.enqueueJSON({ url: "https://example.com", body: { "Hello": "World" } }) ``` -------------------------------- ### POST /v2/queues/{queueName} Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Upserts a queue with a specified parallelism setting. ```APIDOC ## POST /v2/queues/{queueName} ### Description Creates or updates a queue with a defined parallelism level. ### Method POST ### Endpoint /v2/queues/{queueName} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to upsert. #### Request Body - **parallelism** (number) - Required - The number of concurrent messages to process. ### Request Example { "parallelism": 2 } ``` -------------------------------- ### Publish with Rate and Period Limits (TypeScript) Source: https://upstash.com/docs/qstash/features/flowcontrol Use this to publish a JSON message with rate and period limits. The period defaults to 1 second if not specified. ```typescript const client = new Client({ token: "" }); await client.publishJSON({ url: "https://example.com", body: { hello: "world" }, flowControl: { key: "USER_GIVEN_KEY", rate: 10, period: "1m" }, }); ``` -------------------------------- ### Security Schemes Source: https://upstash.com/docs/qstash/api-reference/logs/list-logs Information on the authentication methods supported by the QStash API, including JWT Bearer tokens and query parameter authentication. ```APIDOC ## Security Schemes ### Description This section outlines the security mechanisms employed by the QStash API to authenticate requests. ### Security Schemes - **bearerAuth**: - Type: http - Scheme: bearer - Bearer Format: JWT - Description: QStash authentication token. - **bearerAuthQuery**: - Type: apiKey - In: query - Name: qstash_token - Description: QStash authentication token passed as a query parameter. ``` -------------------------------- ### Enable Content-Based Deduplication using TypeScript Source: https://upstash.com/docs/qstash/features/deduplication When publishing a JSON message with the QStash TypeScript client, set the `contentBasedDeduplication` option to `true`. QStash will then compute a deduplication ID from the message content. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, contentBasedDeduplication: true, }); ``` -------------------------------- ### POST /v2/publish/{url} Source: https://upstash.com/docs/qstash/overall/apiexamples Publishes a message to a specified URL with options for retry counts, custom delay logic, and callback URLs. ```APIDOC ## POST /v2/publish/{url} ### Description Publishes a message to the target URL. Supports configuring retry behavior and callback endpoints for message delivery status. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Path Parameters - **url** (string) - Required - The destination URL to send the message to. #### Request Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Upstash-Retries** (integer) - Optional - Number of times to retry on failure. - **Upstash-Retry-Delay** (string) - Optional - Mathematical expression for delay between retries (e.g., "pow(2, retried) * 1000"). - **Upstash-Callback** (string) - Optional - URL to receive the response from the endpoint. - **Upstash-Failure-Callback** (string) - Optional - URL to receive notification if the endpoint fails. ### Request Example { "hello": "world" } ### Response #### Success Response (200) - **messageId** (string) - The unique identifier for the published message. ``` -------------------------------- ### Implement AWS Lambda Handler for QStash Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs The handler function extracts the signature and signing keys from environment variables, attempting verification with the current key before falling back to the next key. ```typescript import type { APIGatewayEvent, APIGatewayProxyResult } from "aws-lambda" import { createHash, createHmac } from "node:crypto" export const handler = async ( event: APIGatewayEvent, ): Promise => { const signature = event.headers["upstash-signature"] ?? "" const currentSigningKey = process.env.QSTASH_CURRENT_SIGNING_KEY ?? "" const nextSigningKey = process.env.QSTASH_NEXT_SIGNING_KEY ?? "" const url = `https://${event.requestContext.domainName}` try { // Try to verify the signature with the current signing key and if that fails, try the next signing key // This allows you to roll your signing keys once without downtime await verify(signature, currentSigningKey, event.body, url).catch((err) => { console.error( `Failed to verify signature with current signing key: ${err}` ) return verify(signature, nextSigningKey, event.body, url) }) } catch (err) { const message = err instanceof Error ? err.toString() : err return { statusCode: 400, body: JSON.stringify({ error: message }), } } // Add your business logic here return { statusCode: 200, body: JSON.stringify({ message: "Request processed successfully" }), } } ``` -------------------------------- ### URL Group Publish Endpoint Source: https://upstash.com/docs/qstash/howto/webhook Use this format when publishing messages to a URL Group. This allows QStash to forward the request to the configured endpoint(s) within the group, applying any default headers. ```bash https://qstash.upstash.io/v2/publish/?qstash_token= ``` -------------------------------- ### Define Environment Variables for QStash Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Define the expected environment variables for QStash signing keys within the Cloudflare Worker's Env interface. These are required for signature verification. ```typescript export interface Env { QSTASH_CURRENT_SIGNING_KEY: string; QSTASH_NEXT_SIGNING_KEY: string; } ``` -------------------------------- ### Enqueue Anthropic LLM Request with QStash Source: https://upstash.com/docs/qstash/integrations/anthropic Use `client.queue().enqueueJSON` to enqueue an LLM request for asynchronous processing with Anthropic. Ensure the `api` is configured with `llm` and the `anthropic()` provider, and set a `callback` URL. ```typescript import { anthropic, Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const result = await client.queue({ queueName: "your-queue-name" }).enqueueJSON({ api: { name: "llm", provider: anthropic({ token: "" }) }, body: { model: "claude-3-5-sonnet-20241022", messages: [ { role: "user", content: "Generate ideas for a marketing campaign.", }, ], }, callback: "https://example.com/callback", }); console.log(result); ``` -------------------------------- ### Publish Anthropic LLM Request with QStash Source: https://upstash.com/docs/qstash/integrations/anthropic Use `client.publishJSON` to send an LLM request to Anthropic. Specify the `api` with `llm` and the `anthropic()` provider. Use the `Upstash-Callback` header for asynchronous response handling, as streaming is not supported. ```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", }); ``` -------------------------------- ### Publish messages in a batch Source: https://upstash.com/docs/qstash/overall/apiexamples Send multiple messages in a single request to improve efficiency. ```shell curl -XPOST https://qstash.upstash.io/v2/batch \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d ' [ { "destination": "https://example.com/destination1" }, { "destination": "https://example.com/destination2" } ]' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.batchJSON([ { url: "https://example.com/destination1", }, { url: "https://example.com/destination2", }, ]); ``` ```python from qstash import QStash client = QStash("") client.message.batch_json( [ { "url": "https://example.com/destination1", }, { "url": "https://example.com/destination2", }, ] ) # Async version is also available ``` -------------------------------- ### Enable Helicone Observability Source: https://upstash.com/docs/qstash/integrations/llm Integrate Helicone for LLM observability by passing the API key within the analytics configuration during model initialization. ```ts import { Client, custom } from "@upstash/qstash"; const client = new Client({ token: "", }); await client.publishJSON({ api: { name: "llm", provider: custom({ token: "XXX", baseUrl: "https://api.together.xyz", }), analytics: { name: "helicone", token: process.env.HELICONE_API_KEY! }, }, body: { model: "meta-llama/Llama-3-8b-chat-hf", messages: [ { role: "user", content: "hello", }, ], }, callback: "https://oz.requestcatcher.com/", }); ``` -------------------------------- ### Pause and Resume Flow Control Key Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Control message delivery for a specific flow control key. Use `pause` to temporarily stop delivery and `resume` to re-enable it. Verify the pause status using the `is_paused` attribute after operations. Requires an initialized QStash client. ```python from qstash import QStash client = QStash("") # Pause delivery for a flow control key client.flow_control.pause("USER_GIVEN_KEY") info = client.flow_control.get("USER_GIVEN_KEY") print(info.is_paused) # True # Resume delivery client.flow_control.resume("USER_GIVEN_KEY") ``` -------------------------------- ### Set callback URL Source: https://upstash.com/docs/qstash/overall/apiexamples Configure endpoints to receive success or failure responses from the message delivery. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Callback: https://example.com/callback" \ -H "Upstash-Failure-Callback: https://example.com/failure" \ -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", }, callback: "https://example.com/callback", failureCallback: "https://example.com/failure", }); ``` ```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 ``` -------------------------------- ### Cancel Multiple Messages in Bulk using QStash Source: https://upstash.com/docs/qstash/sdks/py/examples/messages Efficiently cancel multiple messages at once by providing a list of message IDs. This method is suitable for batch operations. ```python from qstash import QStash client = QStash("") # cancel more than one message client.message.cancel_many(["", ""]) # cancel all messages client.message.cancel_all() ``` -------------------------------- ### Configure Retry-After Headers Source: https://upstash.com/docs/qstash/features/retry Specify custom retry delays using seconds, duration strings, or RFC1123 dates. Retries are capped at one day. ```http Retry-After: 0 // Next retry will be scheduled immediately without any delay. Retry-After: 10 // Next retry will be scheduled after a 10-second delay. Retry-After: 6m5s // Next retry will be scheduled after 6 minutes 5 seconds delay. Retry-After: Sun, 27 Jun 2024 12:16:24 GMT // Next retry will be scheduled for the specified date, within the allowable limits. ``` -------------------------------- ### Create a schedule with timeout Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Creates a schedule with a specified timeout duration for the request. ```APIDOC ## POST /schedules/create ### Description Creates a schedule with a configurable timeout value for the destination URL. ### Method POST ### Endpoint /schedules/create ### Parameters #### Request Body - **destination** (string) - Required - The destination URL. - **cron** (string) - Required - The cron syntax for the schedule. - **timeout** (string) - Optional - The timeout duration in seconds for the request. ### Request Example ```json { "destination": "https://my-api...", "cron": "* * * * *", "timeout": "30" } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. - **cron** (string) - The cron syntax used. - **destination** (string) - The destination URL. - **timeout** (string) - The timeout duration in seconds. #### Response Example ```json { "scheduleId": "schedule-id-timeout", "cron": "* * * * *", "destination": "https://my-api...", "timeout": "30" } ``` ``` -------------------------------- ### Publish messages to a FIFO queue Source: https://upstash.com/docs/qstash/overall/apiexamples Ensure messages are processed in order by enqueuing them into a specific queue. ```shell 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", }, ) # Async version is also available ``` -------------------------------- ### Submit Documentation Feedback Source: https://upstash.com/docs/qstash/api-reference/flow-control/pin-configuration-for-flow-control-key Submit feedback for incorrect, outdated, or confusing documentation. ```APIDOC ## POST https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback regarding the documentation. ### Method POST ### Endpoint https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Request Body - **path** (string) - Required - The path of the current page for which feedback is being submitted. - **feedback** (string) - Required - A description of the issue encountered in the documentation. ### Request Example ```json { "path": "/current-page-path", "feedback": "The description for the rate parameter is unclear." } ``` ``` -------------------------------- ### Publish HTML Content Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Sends raw HTML content by setting the appropriate Content-Type header. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publish({ url: "https://my-api...", body: "

Hello World

", headers: { "Content-Type": "text/html", }, }); ``` -------------------------------- ### Submit Feedback Source: https://upstash.com/docs/qstash/api-reference/messages/get-a-message Submit feedback regarding the documentation. ```APIDOC ## POST /_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback for documentation issues. ### Method POST ### Endpoint https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Request Body - **path** (string) - Required - The path of the current page. - **feedback** (string) - Required - Description of the issue. ### Request Example ```json { "path": "/current-page-path", "feedback": "Description of the issue" } ``` ``` -------------------------------- ### AWS Lambda Handler for QStash Webhook Verification Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python The main handler function for an AWS Lambda function. It retrieves QStash signing keys from environment variables, parses the incoming event, extracts the signature and URL, and attempts to verify the signature using the provided keys. Returns a 400 error if verification fails. ```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", }), } ``` -------------------------------- ### Publishing Messages with Custom Headers Source: https://upstash.com/docs/qstash/howto/publishing Send a message with custom headers by prefixing them with 'Upstash-Forward-'. ```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", }, ); ``` -------------------------------- ### Publish a message using ngrok URL Source: https://upstash.com/docs/qstash/howto/local-tunnel Use this curl command to publish a message to your application via the ngrok forwarding URL. Replace the URL and bearer token with your actual values. ```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' ``` -------------------------------- ### Pin and Unpin Configuration Source: https://upstash.com/docs/qstash/features/flowcontrol Pin a flow control key's configuration to enforce fixed rate and parallelism settings, preventing individual messages from overriding them. Unpin to allow overrides. ```APIDOC ## Pin and Unpin Configuration ### Description Pinning locks a flow control key's configuration so that incoming messages cannot override it. This is useful when you want to enforce a fixed rate or parallelism regardless of what individual messages request. You can pin only parallelism, only rate, or both. When pinning rate, you can optionally include a `period` (in seconds). Similarly, you can unpin them independently. ### Pin Configuration #### Method POST #### Endpoint `/v2/flowControl/{key}/pin` #### Path Parameters - **key** (string) - Required - The flow control key to pin configuration for. #### Query Parameters - **parallelism** (integer) - Optional - The fixed parallelism value. - **rate** (integer) - Optional - The fixed rate value. - **period** (integer) - Optional - The period in seconds for the rate limit (required if `rate` is specified). ### Unpin Configuration #### Method POST #### Endpoint `/v2/flowControl/{key}/unpin` #### Path Parameters - **key** (string) - Required - The flow control key to unpin configuration from. #### Query Parameters - **parallelism** (boolean) - Optional - Set to `true` to unpin parallelism. - **rate** (boolean) - Optional - Set to `true` to unpin rate. ### Check Pinned Status #### Method GET #### Endpoint `/v2/flowControl/{key}` #### Path Parameters - **key** (string) - Required - The flow control key to get status for. #### Response #### Success Response (200) - **isPinnedParallelism** (boolean) - Indicates if parallelism is pinned. - **isPinnedRate** (boolean) - Indicates if rate is pinned. ### Request Example (Pin) ```bash curl -X POST "https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/pin?parallelism=3&rate=20&period=120" \ -H "Authorization: Bearer " ``` ### Request Example (Unpin) ```bash curl -X POST "https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/unpin?parallelism=true&rate=true" \ -H "Authorization: Bearer " ``` ### Request Example (Check Status) ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // Check pinned status const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info.isPinnedParallelism); // true console.log(info.isPinnedRate); // true ``` ``` -------------------------------- ### Publish a message with a failure callback Source: https://upstash.com/docs/qstash/features/callbacks Configure a failure callback URL to receive notifications when message delivery fails after all retries. ```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} (Relative Delay) Source: https://upstash.com/docs/qstash/features/delay Publishes a message with a relative delay using the Upstash-Delay header. ```APIDOC ## POST /v2/publish/{url} ### Description Delays a message by a specific duration relative to the publication time. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{url} ### Parameters #### Request Headers - **Upstash-Delay** (string) - Optional - Duration format (e.g., 10s, 1m, 2h, 7d). ### 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...' ``` -------------------------------- ### Schedule to a Queue Source: https://upstash.com/docs/qstash/features/schedules Schedule a message to be added to a specific queue at a set time. ```typescript curl -XPOST \ import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", cron: "* * * * *", queueName: "yourQueueName", }); ``` ```bash curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Cron: * * * * *" \ -H "Upstash-Queue-Name: yourQueueName" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/schedules/https://example.com' ``` -------------------------------- ### POST /v2/keys/rotate Source: https://upstash.com/docs/qstash/api-reference/signing-keys/rotate-signing-keys Rotates the current signing keys. During rotation, the next key becomes the current key, and a new next key is generated. ```APIDOC ## POST /v2/keys/rotate ### Description Rotate your signing keys to switch the keys used to sign messages without causing downtime. This ensures that signatures remain valid and that the application can continue verifying new messages seamlessly. ### Method POST ### Endpoint /v2/keys/rotate ### Response #### Success Response (200) - **current** (string) - The current signing key. - **next** (string) - The next signing key. #### Response Example { "current": "string", "next": "string" } ``` -------------------------------- ### List Flow Control Keys Source: https://upstash.com/docs/qstash/api-reference/flow-control/list-flow-control-keys This endpoint allows you to retrieve a list of all active flow control keys. Each key provides insights into message queuing, parallelism, and rate limiting configurations. ```APIDOC ## GET /v2/flowControl ### Description List all Flow Control keys. ### Method GET ### Endpoint /v2/flowControl ### Parameters #### Query Parameters - **qstash_token** (string) - Required - QStash authentication token passed as a query parameter ### Request Example (No request body for GET request) ### 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. #### Response Example ```json [ { "flowControlKey": "my-key", "waitListSize": 0, "parallelismMax": 10, "parallelismCount": 2, "rateMax": 100, "rateCount": 50, "ratePeriod": 60, "ratePeriodStart": 1678886400, "isPinnedParallelism": false, "isPinnedRate": false, "isPaused": false } ] ``` ``` -------------------------------- ### Submit Documentation Feedback Source: https://upstash.com/docs/qstash/api-reference/flow-control/get-flow-control-key Submit feedback regarding the documentation. Use this endpoint to report incorrect, outdated, or confusing information. ```APIDOC ## POST https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback for the current documentation page. ### Method POST ### Endpoint /docs/_mintlify/feedback/upstash/agent-feedback ### Request Body - **path** (string) - Required - The path of the current page for which feedback is being submitted. - **feedback** (string) - Required - A description of the issue or suggestion. ### Request Example ```json { "path": "/current-page-path", "feedback": "The description for the rateMax parameter is unclear." } ``` ``` -------------------------------- ### Failure Callback and Redaction Configuration Source: https://upstash.com/docs/qstash/api-reference/schedules/create-a-schedule Details on how to configure failure callbacks and redact sensitive fields using request headers. ```APIDOC ## Failure Callback and Redaction Headers ### Description Configure how QStash handles failure callbacks and sensitive data redaction using specific request headers. ### Headers - **Upstash-Failure-Callback-Forward-* (string)** - Optional - Prefix header name with this to forward custom headers to the failure callback URL. - **Upstash-Failure-Callback-Method (string)** - Optional - HTTP method for the callback request (Default: POST). - **Upstash-Failure-Callback-Timeout (string)** - Optional - Timeout for the callback request. - **Upstash-Failure-Callback-Retries (integer)** - Optional - Number of retries for the callback request. - **Upstash-Failure-Callback-Retry-Delay (string)** - Optional - Retry delay for the callback request. - **Upstash-Redact-Fields (string)** - Optional - Comma-separated list of fields to redact (e.g., 'body', 'headers', 'header[Authorization]'). ### Request Body - **payload** (text/plain, application/json, or application/octet-stream) - Required - The raw request message to be delivered. ### Response #### Success Response (200) - **scheduleId** (string) - Unique identifier for the created schedule. #### Error Response (400) - **error** (string) - Error message for invalid schedule IDs. #### Error Response (412) - **error** (string) - Error message for exceeding maximum schedule limits. ``` -------------------------------- ### Pause and Resume a Queue Source: https://upstash.com/docs/qstash/sdks/py/examples/queues Use this snippet to pause or resume a queue. Note that pausing or resuming a queue may take up to a minute to complete, so avoid these operations during critical processes. ```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) ``` -------------------------------- ### Batching messages with URL Groups Source: https://upstash.com/docs/qstash/features/batch Include URL Groups as destinations within a batch request. ```shell curl -XPOST https://qstash.upstash.io/v2/batch \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d ' [ { "destination": "myUrlGroup" }, { "destination": "https://example.com/destination2" } ]' ``` ```typescript const client = new Client({ token: "" }); // Each message is the same as the one you would send with the publish endpoint const res = await client.batchJSON([ { urlGroup: "myUrlGroup", }, { url: "https://example.com/destination2", }, ]); ``` ```python from qstash import QStash client = QStash("") client.message.batch_json( [ {"url_group": "my-url-group"}, {"url": "https://example.com/destination2"}, ] ) ``` -------------------------------- ### Python Redis Cleanup Logic Source: https://upstash.com/docs/qstash/quickstarts/python-vercel Python code to connect to Upstash Redis and delete all keys. Ensure you replace 'YOUR_REDIS_URL' and 'YOUR_TOKEN' with your actual credentials. ```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() ``` -------------------------------- ### Configure Custom Retry Delay Source: https://upstash.com/docs/qstash/features/retry Override the default backoff algorithm by providing a mathematical expression for the delay. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Retries: 3" \ -H "Upstash-Retry-Delay: pow(2, retried) * 1000" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, retries: 3, retryDelay: "pow(2, retried) * 1000", // 2^retried * 1000ms }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, retries=3, retry_delay="pow(2, retried) * 1000", # 2^retried * 1000ms ); ``` -------------------------------- ### Verify QStash JWT in Python Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python Validates the JWT signature, issuer, subject, expiration, and body hash for incoming QStash requests. ```python # @param url - The public URL of the lambda function def verify(jwt_token, signing_key, body, url): split = jwt_token.split(".") if len(split) != 3: raise Exception("Invalid JWT.") header, payload, signature = split message = header + '.' + payload generated_signature = base64.urlsafe_b64encode(hmac.new(bytes(signing_key, 'utf-8'), bytes(message, 'utf-8'), digestmod=hashlib.sha256).digest()).decode() if generated_signature != signature and signature + "=" != generated_signature : raise Exception("Invalid JWT signature.") decoded = jwt.decode(jwt_token, options={"verify_signature": False}) sub = decoded['sub'] iss = decoded['iss'] exp = decoded['exp'] nbf = decoded['nbf'] decoded_body = decoded['body'] if iss != "Upstash": raise Exception("Invalid issuer: {}".format(iss)) if sub.rstrip("/") != url.rstrip("/"): raise Exception("Invalid subject: {}".format(sub)) now = time.time() if now > exp: raise Exception("Token has expired.") if now < nbf: raise Exception("Token is not yet valid.") if body != None: while decoded_body[-1] == "=": decoded_body = decoded_body[:-1] m = hashlib.sha256() m.update(bytes(body, 'utf-8')) m = m.digest() generated_hash = base64.urlsafe_b64encode(m).decode() if generated_hash != decoded_body and generated_hash != decoded_body + "=" : raise Exception("Body hash doesn't match.") ``` -------------------------------- ### Exponential Backoff Formula Source: https://upstash.com/docs/qstash/features/retry The default retry delay calculation based on the number of retries. ```text n = how many times this request has been retried delay = min(86400, e ** (2.5*n)) // in seconds ``` -------------------------------- ### Create a schedule with cron Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Configures a recurring task using a cron expression. The destination can be a URL or a URL group. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://my-api...", cron: "*/5 * * * *", }); ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "my-url-group", cron: "* * * * *", }); ``` -------------------------------- ### Configure Retry Backoff Expressions Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Use these expressions to define custom retry intervals. The 'retried' variable tracks the number of failed attempts. ```text 1000 ``` ```text 1000 * (1 + retried) ``` ```text pow(2, retried) * 1000 ``` ```text max(1000, pow(2, retried) * 100) ``` -------------------------------- ### Combine Rate, Parallelism, and Period with cURL Source: https://upstash.com/docs/qstash/features/flowcontrol Set combined flow control parameters including rate, parallelism, and period using the `Upstash-Flow-Control-Value` header in your cURL request. Ensure the correct format for each parameter. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:rate=10,parallelism=20,period=1m" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` -------------------------------- ### Resume Queue OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/queues/resume-queue This OpenAPI specification defines the POST request to resume a queue. It includes parameters, responses, and security schemes. ```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.upstash.io 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}/resume: post: tags: - Queues summary: Resume Queue description: Resumes a queue to starts the delivery of enqueued messages parameters: - name: queueName in: path required: true schema: type: string description: The name of the queue to resume. responses: '200': description: Queue resumed successfully '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' 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 ``` -------------------------------- ### QStash OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message The OpenAPI 3.1.0 specification for the QStash REST API. This defines the structure and available operations for publishing and managing messages, queues, and schedules. ```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.upstash.io 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/enqueue/{queueName}/{destination}: post: tags: - Messages summary: Enqueue a Message description: Enqueue a message to the specified queue parameters: - name: queueName in: path required: true schema: type: string description: >- The name of the queue that message will be enqueued on. If doesn't exist, it will be created automatically with default parallelism. - 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. Note that destination must be publicly accessible over the internet. If you are working with local endpoints, consider using QStash local development server or a public tunnel service. - name: queueName in: path required: true schema: type: string description: The name of the queue to enqueue the message to. - 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-Forward-* in: header schema: type: string description: > You can send custom headers to your endpoint along with your message. To send a custom header, prefix the header name with `Upstash-Forward-`. We will strip prefix and send them to the destination. | Header | Forwarded To Destination As | |--------|--------------| | Upstash-Forward-My-Header: my-value | My-Header: my-value | | Upstash-Forward-Authorization: Bearer | Authorization: Bearer | - 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 - 1d1h30m 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](https://upstash.com/pricing/qstash). The format of this header is `` where value is a number and unit is one of: - `s` for seconds - `m` for minutes - `h` for hours. - name: Upstash-Retries in: header schema: type: integer description: > ``` -------------------------------- ### QStash Signature Verification Function Stub Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/python A placeholder comment for the `verify` function, which is responsible for the actual cryptographic verification of the QStash signature. This function would typically use the provided JWT token, signing key, request body, and URL to confirm the request's authenticity. ```python # @param jwt_token - The content of the `upstash-signature` header # @param signing_key - The signing key to use to verify the signature (Get it from Upstash Console) # @param body - The raw body of the request ``` -------------------------------- ### Submit Feedback Source: https://upstash.com/docs/qstash/sdks/py/examples/messages Allows users to submit feedback regarding documentation. This endpoint is for reporting issues with the documentation content. ```APIDOC ## POST /_mintlify/feedback/upstash/agent-feedback ### Description Submits feedback about the current documentation page. Use this to report incorrect, outdated, or confusing information. ### Method POST ### Endpoint `https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback` ### Parameters #### Request Body - **path** (string) - Required - The path of the current documentation page. - **feedback** (string) - Required - A description of the issue or feedback. ### Request Example ```json { "path": "/current-page-path", "feedback": "Description of the issue" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating feedback was received. #### Response Example ```json { "message": "Feedback received successfully." } ``` ``` -------------------------------- ### Paginate Through All Logs Source: https://upstash.com/docs/qstash/sdks/ts/examples/logs Retrieve all logs by iterating through results using a cursor. This is useful when dealing with a potentially large number of logs. ```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; } } ``` -------------------------------- ### Configure Flow Control Value Header Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Format for the Upstash-Flow-Control-Value header to define rate limiting parameters. ```text parallelism=, rate=, period= ``` -------------------------------- ### Configure Retries Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Sets the maximum number of retries for a message. The retry limit is constrained by your QStash plan. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, retries: 1, }); ``` -------------------------------- ### Message Properties Source: https://upstash.com/docs/qstash/api-reference/logs/list-logs Details about the properties of a message within QStash, including its content, state, delivery information, and associated metadata. ```APIDOC ## Message Properties ### Description This section details the various properties associated with a message in QStash, covering its content, state, delivery parameters, and any associated metadata. ### Properties - **body** (string) - Base64 encoded body of the message. - **state** (string) - Enum: CREATED, ACTIVE, RETRY, ERROR, DELIVERED, FAILED, CANCEL_REQUESTED, CANCELLED. The state of the message at the time of the log entry. - **error** (string) - The error message if the log entry corresponds to an error state. - **nextDeliveryTime** (integer, int64) - The next scheduled time of the message. (Unix timestamp in milliseconds) - **url** (string) - The URL to which the message is being 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. - **scheduleId** (string) - The scheduleId of the message if the message is triggered by a schedule. - **queueName** (string) - The name of the queue if the message is enqueued to a queue. - **responseStatus** (integer) - The status code of the response. Only set if the state is ERROR. - **responseBody** (string) - The base64 encoded body of the response. Only set if the state is ERROR. - **responseHeaders** (object) - The headers of the response. Only set if the state is ERROR. - **timeout** (integer) - The timeout (in milliseconds) of the outgoing http requests, after which Qstash cancels the request. - **method** (string) - HTTP method of the message for outgoing request. - **callback** (string) - Callback is the URL address where QStash sends the response of a publish. - **callbackHeaders** (object) - The headers sent to the callback URL. - **failureCallback** (string) - FailureCallback is the URL address where QStash sends the response of a failed message after all retries are exhausted. - **failureCallbackHeaders** (object) - The headers sent to the failure callback URL. - **maxRetries** (integer) - The maximum number of retries for the message. - **retryDelayExpression** (string) - The retry delay expression used for calculating retry delays. - **label** (string) - The label assigned to the message. ``` -------------------------------- ### Complete Cloudflare Worker Handler with Signature Verification Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers This is the complete Cloudflare Worker handler function that imports the QStash Receiver, initializes it with signing keys, verifies the incoming request signature, and returns a response. It handles invalid signatures by returning a 401 status. ```typescript 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; ``` -------------------------------- ### Publish Message to Endpoint using cURL Source: https://upstash.com/docs/qstash/overall/apiexamples Use this cURL command to publish a JSON message to a specific endpoint. Ensure you replace 'XXX' with your actual authorization token. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://example.com' ``` -------------------------------- ### Submit Feedback Request Body Source: https://upstash.com/docs/qstash/api-reference/flow-control/pause-flow-control-key JSON structure for submitting feedback regarding documentation issues. ```json { "path": "/current-page-path", "feedback": "Description of the issue" } ``` -------------------------------- ### Message Object Schema Source: https://upstash.com/docs/qstash/api-reference/dlq/list-dlq-messages Defines the structure of a message object in QStash, including metadata, delivery configuration, and response tracking. ```APIDOC ## Message Object Schema ### Description Represents the structure of a message within the QStash system, containing delivery details, flow control settings, and execution results. ### Properties - **body** (string) - The body of the message if it is composed of utf8 chars only. - **bodyBase64** (string) - The base64 encoded body if the body contains a non-utf8 char. - **maxRetries** (integer) - The number of retries 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 a callback is sent each time the message is attempted to be delivered. - **failureCallback** (string) - The url where a callback is sent after the message has failed. - **queueName** (string) - The name of the queue if the message is enqueued. - **scheduleId** (string) - The scheduleId 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. - **responseBody** (string) - The body of the response if it is composed of utf8 chars only. - **responseBodyBase64** (string) - The base64 encoded body of the response if the body contains a non-utf8 char. ``` -------------------------------- ### Publish a message with an absolute delay Source: https://upstash.com/docs/qstash/features/delay Use the Upstash-Not-Before header or client-specific notBefore parameters to schedule delivery at a specific Unix timestamp. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Not-Before: 1657104947" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/https://my-api...' ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, notBefore: 1657104947, }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://my-api...", body={ "hello": "world", }, headers={ "test-header": "test-value", }, not_before=1657104947, ) ``` -------------------------------- ### Retrieve schedule information Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Fetches details for a specific schedule by its ID or lists all existing schedules. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.schedules.get("scheduleId"); console.log(res.cron); ``` ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const allSchedules = await client.schedules.list(); console.log(allSchedules); ``` -------------------------------- ### Verify requests in Next.js App Router Source: https://upstash.com/docs/qstash/howto/multi-region Use the verifySignatureAppRouter helper to automatically handle request verification and multi-region headers in Next.js. ```typescript import { verifySignatureAppRouter } from "@upstash/qstash/nextjs"; export const POST = verifySignatureAppRouter(async (req) => { const body = await req.json(); return Response.json({ success: true }); }); ``` -------------------------------- ### Create/overwrite a schedule with a user chosen schedule id Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Creates or replaces an existing schedule with a user-defined schedule ID. ```APIDOC ## POST /schedules/create ### Description Creates a new schedule or overwrites an existing one using a provided schedule ID. ### Method POST ### Endpoint /schedules/create ### Parameters #### Request Body - **destination** (string) - Required - The destination URL or URL group. - **scheduleId** (string) - Required - The user-defined ID for the schedule. - **cron** (string) - Required - The cron syntax for the schedule. ### Request Example ```json { "destination": "https://example.com", "scheduleId": "USER_PROVIDED_SCHEDULE_ID", "cron": "* * * * *" } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created or overwritten schedule. - **cron** (string) - The cron syntax used. - **destination** (string) - The destination URL or URL group. #### Response Example ```json { "scheduleId": "USER_PROVIDED_SCHEDULE_ID", "cron": "* * * * *", "destination": "https://example.com" } ``` ``` -------------------------------- ### Configure AWS CDK Stack for Lambda and API Gateway Source: https://upstash.com/docs/qstash/quickstarts/aws-lambda/nodejs Defines a CDK stack that creates a Node.js Lambda function and exposes it via an API Gateway REST API. ```ts import * as cdk from "aws-cdk-lib"; import * as lambda from "aws-cdk-lib/aws-lambda"; import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"; import { Construct } from "constructs"; import path from "path"; import * as apigateway from 'aws-cdk-lib/aws-apigateway'; export class VideoProcessingStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props) // Create the Lambda function const videoProcessingLambda = new NodejsFunction(this, 'VideoProcessingLambda', { runtime: lambda.Runtime.NODEJS_20_X, handler: 'handler', entry: path.join(__dirname, '../lambda/index.ts'), }); // Create the API Gateway const api = new apigateway.RestApi(this, 'VideoProcessingApi', { restApiName: 'Video Processing Service', description: 'This service handles video processing.', defaultMethodOptions: { authorizationType: apigateway.AuthorizationType.NONE, }, }); api.root.addMethod('POST', new apigateway.LambdaIntegration(videoProcessingLambda)); } } ``` -------------------------------- ### POST /v2/flowControl/{flowControlKey}/unpin Source: https://upstash.com/docs/qstash/api-reference/flow-control/unpin-configuration-for-flow-control-key Removes the pinned configuration for a specific flow-control key. This allows QStash to resume updating configurations based on incoming messages. ```APIDOC ## POST /v2/flowControl/{flowControlKey}/unpin ### Description Removes the pinned configuration for a specific flow-control key. After unpinning, the system resumes the default behavior and updates the configuration based on configurations provided by incoming messages. ### Method POST ### Endpoint /v2/flowControl/{flowControlKey}/unpin ### Parameters #### Path Parameters - **flowControlKey** (string) - Required - The flow-control key for which the configuration will be unpinned. #### Query Parameters - **parallelism** (boolean) - Optional - Defaults to `false`. The flag to indicate whether to unpin the parallelism configuration. - **rate** (boolean) - Optional - Defaults to `false`. The flag to indicate whether to unpin the rate configuration. ### Request Example ```json { "example": "POST /v2/flowControl/my-key/unpin?parallelism=true&rate=true" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the configuration was successfully unpinned. #### Response Example ```json { "example": "Flow control configuration for key 'my-key' unpinned successfully." } ``` #### Error Response (400) - **error** (string) - Bad request. Returned when the flow-control key is not provided. #### Error Response Example ```json { "example": { "error": "Flow control key is required." } } ``` ``` -------------------------------- ### Set Parallelism Limit with cURL Source: https://upstash.com/docs/qstash/features/flowcontrol Use the `Upstash-Flow-Control-Value` header with `parallelism=N` to set the concurrency limit when publishing messages via cURL. Replace `XXX` with your actual token. ```bash curl -XPOST -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -H "Upstash-Flow-Control-Key:USER_GIVEN_KEY" \ -H "Upstash-Flow-Control-Value:parallelism=10" \ 'https://qstash.upstash.io/v2/publish/https://example.com' \ -d '{"message":"Hello, World!"}' ``` -------------------------------- ### POST /v2/publish/{destination} Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Publish a message to a specified destination, which can be a URL or a URL Group. ```APIDOC ## POST /v2/publish/{destination} ### Description Publish a message to the specified destination. ### Method POST ### Endpoint /v2/publish/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - 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. Note that destination must be publicly accessible over the internet. #### Header Parameters - **Content-Type** (string) - Optional - `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`. - **Upstash-Forward-** (string) - Optional - You can send custom headers to your endpoint along with your message. To send a custom header, prefix the header name with `Upstash-Forward-`. We will strip prefix and send them to the destination. - **Upstash-Method** (string) - Optional - The HTTP method to use when sending the request to your API. Allowed values: GET, POST, PUT, PATCH, DELETE. Defaults to POST. - **Upstash-Timeout** (string) - Optional - Specifies the maximum duration the request is allowed to take before timing out. The format of this header is `` where value is a number and unit is one of: `s` (seconds), `m` (minutes), `h` (hours). - **Upstash-Retries** (integer) - Optional - How many times should this message be retried in case the destination API returns an error or is not available. The total number of deliveries is 1 (initial attempt) + retries. If it is not provided, the plan default retry value will be used. - **Upstash-Retry-Delay** (string) - Optional - Specifies the delay between retries. ### Request Body (The request body schema is not provided in the source text) ### Response #### Success Response (200) (Response schema is not provided in the source text) #### Error Response (Error response schema is not provided in the source text) ``` -------------------------------- ### Batching messages with a queue Source: https://upstash.com/docs/qstash/features/batch Send multiple messages to specific queues using the batch endpoint. ```shell curl -XPOST https://qstash.upstash.io/v2/batch \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d ' [ { "queue": "my-queue", "destination": "https://example.com/destination1" }, { "queue": "my-second-queue", "destination": "https://example.com/destination2" } ]' ``` ```typescript const client = new Client({ token: "" }); const res = await client.batchJSON([ { queueName: "my-queue", url: "https://example.com/destination1", }, { queueName: "my-second-queue", url: "https://example.com/destination2", }, ]); ``` ```python from upstash_qstash import QStash from upstash_qstash.message import BatchRequest qstash = QStash("") messages = [ BatchRequest( queue="my-queue", url="https://httpstat.us/200", body=f"hi 1", retries=0 ), BatchRequest( queue="my-second-queue", url="https://httpstat.us/200", body=f"hi 2", retries=0 ), ] qstash.message.batch(messages) ``` -------------------------------- ### Combine Rate, Parallelism, and Period in TypeScript Source: https://upstash.com/docs/qstash/features/flowcontrol Configure message delivery by specifying `rate`, `parallelism`, and `period` within the `flowControl` object. The `period` is specified in minutes (e.g., '1m'). ```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" }, }); ``` -------------------------------- ### Unpin configuration Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Removes the fixed configuration lock for parallelism or rate settings independently. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // Unpin parallelism and rate (can unpin independently) await client.flowControl.unpin("USER_GIVEN_KEY", { parallelism: true, rate: true, }); ``` -------------------------------- ### Handling Background Jobs with Error Catching and UI State Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs Updated server action with error handling and a client-side component to manage loading 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}

}
); } ``` -------------------------------- ### POST /v2/queues/{queueName}/pause and /resume Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Endpoints to pause or resume message processing for a specific queue. ```APIDOC ## POST /v2/queues/{queueName}/pause ### Description Pauses the processing of messages in the specified queue. ### Method POST ### Endpoint /v2/queues/{queueName}/pause ## POST /v2/queues/{queueName}/resume ### Description Resumes the processing of messages in the specified queue. ### Method POST ### Endpoint /v2/queues/{queueName}/resume ``` -------------------------------- ### Create Background Job Endpoint Source: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs A POST route handler that processes a background task by performing multiple fetch requests with delays. ```ts export async function POST(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 }) } ``` -------------------------------- ### Create a schedule with a timeout Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Sets a specific timeout duration in seconds for the request triggered by the schedule. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ url: "https://my-api...", cron: "* * * * *", timeout: "30" // 30 seconds timeout }); ``` -------------------------------- ### Verify QStash Signature Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Verify the signature of an incoming request using the QStash Receiver. This involves retrieving the signature from the 'Upstash-Signature' header and the request body. ```typescript const body = await request.text(); const isValid = await receiver.verify({ signature: request.headers.get("Upstash-Signature")!, body, }); ``` -------------------------------- ### Publish to a URL Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Publishes a JSON payload to a specific URL with a delay and custom headers. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world" }, headers: { "test-header": "test-value" }, delay: "3s", }); ``` -------------------------------- ### POST /url-groups/add-endpoints Source: https://upstash.com/docs/qstash/sdks/ts/examples/url-groups Creates a new URL group or adds endpoints to an existing one. ```APIDOC ## POST /url-groups/add-endpoints ### Description Creates a new URL group with the specified name and adds the provided list of endpoints to it. ### Method POST ### Request Body - **name** (string) - Required - The name of the URL group. - **endpoints** (array) - Required - A list of objects containing the URL for each endpoint. ``` -------------------------------- ### QStash API Authorization Header Source: https://upstash.com/docs/qstash/features/security Include your QStash token in the Authorization header as a Bearer token for all API requests. ```http "Authorization": "Bearer " ``` -------------------------------- ### Define QStash OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/url-groups/list-url-groups The OpenAPI YAML definition for the QStash REST API, including security schemes and URL Group endpoints. ```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.upstash.io 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 ``` -------------------------------- ### Rotate Signing Keys Source: https://upstash.com/docs/qstash/sdks/py/examples/keys Rotates the signing keys, generating a new current and next key. ```APIDOC ## POST /v1/signing-key/rotate ### Description Rotates the signing keys, invalidating the current key and generating a new current and next key. ### Method POST ### Endpoint /v1/signing-key/rotate ### Request Example ```python from qstash import QStash client = QStash("") new_signing_key = client.signing_key.rotate() print(new_signing_key.current, new_signing_key.next) ``` ### Response #### Success Response (200) - **current** (string) - The newly generated current signing key. - **next** (string) - The newly generated next signing key. #### Response Example ```json { "current": "your_new_current_signing_key", "next": "your_new_next_signing_key" } ``` ``` -------------------------------- ### Publish Message with Delay using cURL Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message with a 5-minute delay using cURL. The 'Upstash-Delay' header specifies the delay duration. Replace 'XXX' with your authorization token. ```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' ``` -------------------------------- ### List DLQ Messages with Filters Source: https://upstash.com/docs/qstash/sdks/ts/examples/dlq Filter DLQ messages by URL or response status, and paginate results using count and order. You can also fetch specific DLQ messages by providing their IDs. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // filter and paginate with top-level options const res = await client.dlq.listMessages({ count: 10, order: "latestFirst", filter: { url: "https://example.com" } }) // fetch specific DLQ messages by ID const res2 = await client.dlq.listMessages({ dlqIds: ["dlq-id-1", "dlq-id-2"] }) ``` -------------------------------- ### Pin a fixed configuration Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Locks the parallelism and rate settings for a key to prevent overrides from incoming messages. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // Pin parallelism and rate so incoming messages cannot override them await client.flowControl.pin("USER_GIVEN_KEY", { parallelism: 3, rate: 20, period: 120, // seconds }); const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info.isPinnedParallelism); // true console.log(info.isPinnedRate); // true ``` -------------------------------- ### Send batch emails with Resend Source: https://upstash.com/docs/qstash/integrations/resend Sends multiple emails in a single request by setting the batch option to true in the provider configuration. ```typescript await client.publishJSON({ api: { name: "email", provider: resend({ token: "", batch: true }), }, body: [ { from: "Acme ", to: ["foo@gmail.com"], subject: "Hello World", html: "

It works!

", }, { from: "Acme ", to: ["bar@outlook.com"], subject: "World Hello", html: "

It works!

", }, ], }); ``` -------------------------------- ### Set custom retry delay Source: https://upstash.com/docs/qstash/overall/apiexamples Customize the interval between retries using mathematical expressions and the 'retried' variable. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Upstash-Retries: 3" \ -H "Upstash-Retry-Delay: pow(2, retried) * 1000" \ -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", }, retries: 3, retryDelay: "pow(2, retried) * 1000", // 2^retried * 1000ms }); ``` ```python from qstash import QStash client = QStash("") client.message.publish_json( url="https://example.com", body={ "hello": "world", }, retries=3, retry_delay="pow(2, retried) * 1000", # 2^retried * 1000ms ) # Async version is also available ``` -------------------------------- ### Retrieve a Message Source: https://upstash.com/docs/qstash/sdks/py/examples/messages Fetches a specific message from QStash using its unique ID. Messages are only available for retrieval while they are being delivered or retried. ```APIDOC ## GET /messages/{msg-id} ### Description Retrieves a specific message by its ID. This is useful for inspecting messages that are currently in the delivery or retry process. ### Method GET ### Endpoint `/messages/{msg-id}` ### Parameters #### Path Parameters - **msg-id** (string) - Required - The unique identifier of the message to retrieve. ### Response #### Success Response (200) - **message** (object) - The retrieved message object. #### Response Example ```json { "message": { "id": "", "body": "...", "contentType": "application/json", "deduplicationId": "", "delay": 0, "notBefore": 0, "callback": "", "headers": {}, "createdAt": 1678886400, "redelivery": 0, "tags": [] } } ``` ``` -------------------------------- ### Retry Delay Customization Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Customizing the retry backoff strategy using mathematical expressions. ```APIDOC ## Retry Delay Customization ### Description Override the default exponential backoff by providing a mathematical expression to compute the next delay. The `retried` variable represents the number of failed attempts (0 for the first retry). ### Supported Functions - `pow(x, y)`: x raised to the power of y - `exp(x)`: e raised to the power of x - `sqrt(x)`: Square root of x - `abs(x)`: Absolute value of x - `floor(x)`: Largest integer <= x - `ceil(x)`: Smallest integer >= x - `round(x)`: Nearest integer - `min(x, y)`: Smaller of x and y - `max(x, y)`: Larger of x and y ### Examples - `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 ``` -------------------------------- ### Configure Failure Callbacks for Message Publishing Source: https://upstash.com/docs/qstash/howto/handling-failures Specify a callback URL to receive notifications when a message fails to be published. This allows for custom error handling or alerting logic. ```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/topics/{urlGroupName}/endpoints Source: https://upstash.com/docs/qstash/api-reference/url-groups/upsert-url-group-and-endpoint Adds one or multiple endpoints to a specified URL Group. If the URL Group does not exist, it is automatically created. ```APIDOC ## POST /v2/topics/{urlGroupName}/endpoints ### Description Add one or multiple endpoints to a URL Group. If the URL Group does not exist, it will be created. ### Method POST ### Endpoint /v2/topics/{urlGroupName}/endpoints ### Parameters #### Path Parameters - **urlGroupName** (string) - Required - The name of your URL Group. #### Request Body - **endpoints** (array) - Required - List of endpoints to add. - **url** (string) - Required - The URL of the endpoint. - **name** (string) - Optional - Optional name for the endpoint. ### Response #### Success Response (200) - **message** (string) - Endpoint(s) added successfully ``` -------------------------------- ### Publishing to URL Groups Source: https://upstash.com/docs/qstash/howto/publishing Publish a single message to multiple endpoints by using a URL group name instead of a specific URL. ```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", }, ); ``` -------------------------------- ### Unpin configuration Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Unpins specific configurations (parallelism and/or rate) from a flow control key, allowing incoming messages to influence these settings again. ```APIDOC ## Unpin configuration ### Description Unpins specific configurations (parallelism and/or rate) from a flow control key, allowing incoming messages to influence these settings again. ### Method POST ### Endpoint /v1/flowcontrol/{key}/unpin ### Parameters #### Path Parameters - **key** (string) - Required - The unique identifier for the flow control key. #### Request Body - **parallelism** (boolean) - Optional - Set to `true` to unpin the parallelism configuration. - **rate** (boolean) - Optional - Set to `true` to unpin the rate configuration. ### Request Example ```json { "parallelism": true, "rate": true } ``` ### Response #### Success Response (200) Indicates that the operation was successful. The response body is typically empty. ``` -------------------------------- ### Pause and resume a schedule Source: https://upstash.com/docs/qstash/sdks/py/examples/schedules Toggles 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) ``` -------------------------------- ### Trigger background job from Next.js client Source: https://upstash.com/docs/qstash/features/background-jobs Use this client-side component in Next.js to initiate a background job by sending a POST request to your server API. ```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 (
); } ``` -------------------------------- ### POST /v2/publish/{destination} Source: https://upstash.com/docs/qstash/howto/publishing Publishes a message to a specific destination URL or a URL group. The message body is passed as-is, and custom headers can be forwarded using the 'Upstash-Forward-' prefix. ```APIDOC ## POST /v2/publish/{destination} ### Description Publishes a message to a destination URL or a URL group. The message is stored durably and delivered to the target API. If the target is unavailable, QStash handles retries automatically. ### Method POST ### Endpoint https://qstash.upstash.io/v2/publish/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - The destination URL (must include protocol) or the name of a URL Group. #### Request Body - **body** (any) - Required - The message payload to be delivered to the destination. ### Request Example ```json { "hello": "world" } ``` ### Response #### Success Response (200) - **message_id** (string) - The unique identifier for the published message. ``` -------------------------------- ### Monitor Worker Logs Source: https://upstash.com/docs/qstash/quickstarts/cloudflare-workers Use Wrangler tail to observe incoming requests and logs from the deployed worker. ```bash $ npx wrangler tail ⛅️ wrangler 4.43.0 -------------------- Successfully created tail, expires at 2025-10-16T00:25:17Z Connected to , waiting for logs... POST https://..workers.dev/ - Ok @ 10/15/2025, 10:34:55 PM ``` -------------------------------- ### Pause and resume Source: https://upstash.com/docs/qstash/sdks/ts/examples/flow-control Temporarily halts message delivery for a specific key and resumes it when ready. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // Pause delivery for a flow control key await client.flowControl.pause("USER_GIVEN_KEY"); const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info.isPaused); // true // Resume delivery await client.flowControl.resume("USER_GIVEN_KEY"); ``` -------------------------------- ### Pin a fixed configuration Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Pins a fixed configuration for parallelism and rate limiting to a flow control key, preventing incoming messages from overriding these settings. ```APIDOC ## Pin a fixed configuration ### Description Pins a fixed configuration for parallelism and rate limiting to a flow control key, preventing incoming messages from overriding these settings. ### Method POST ### Endpoint /v1/flowcontrol/{key}/pin ### Parameters #### Path Parameters - **key** (string) - Required - The unique identifier for the flow control key. #### Request Body - **parallelism** (integer) - Optional - The fixed maximum number of concurrent messages. - **rate** (integer) - Optional - The fixed maximum number of messages allowed within the specified rate period. - **period** (integer) - Optional - The duration of the rate limiting period in seconds. ### Request Example ```json { "parallelism": 3, "rate": 20, "period": 120 } ``` ### Response #### Success Response (200) Indicates that the operation was successful. The response body is typically empty. ``` -------------------------------- ### Resume Schedule OpenAPI Specification Source: https://upstash.com/docs/qstash/api-reference/schedules/resume-a-schedule This OpenAPI specification defines the endpoint for resuming a paused schedule. It includes request parameters, response codes, and security schemes. ```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.upstash.io 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}/resume: post: tags: - Schedules summary: Resume a Schedule description: Resume a paused Schedule parameters: - name: scheduleId in: path required: true schema: type: string description: The ID of the schedule to resume. responses: '200': description: Schedule resumed successfully 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 ``` -------------------------------- ### Batching messages with destinations Source: https://upstash.com/docs/qstash/features/batch Send multiple messages to specific destinations 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": "https://example.com/destination1" }, { "destination": "https://example.com/destination2" } ]' ``` ```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", }, ]); ``` ```python from qstash import QStash client = QStash("") client.message.batch_json( [ {"url": "https://example.com/destination1"}, {"url": "https://example.com/destination2"}, ] ) ``` -------------------------------- ### List URL Groups Source: https://upstash.com/docs/qstash/api-reference/url-groups/list-url-groups Lists all your URL Groups. This endpoint is part of the URL Groups API. ```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" } ] } ]" } ``` ``` -------------------------------- ### Pin and Unpin Configuration Source: https://upstash.com/docs/qstash/features/flowcontrol Lock flow control configurations to prevent overrides by incoming messages. You can pin or unpin parallelism and rate settings independently. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); // Pin a fixed configuration await client.flowControl.pin("USER_GIVEN_KEY", { parallelism: 3, rate: 20, period: 120, // seconds }); // Check pinned status const info = await client.flowControl.get("USER_GIVEN_KEY"); console.log(info.isPinnedParallelism); // true console.log(info.isPinnedRate); // true // Unpin specific configs await client.flowControl.unpin("USER_GIVEN_KEY", { parallelism: true, rate: true, }); ``` ```python from qstash import QStash client = QStash("") # Pin a fixed configuration client.flow_control.pin( "USER_GIVEN_KEY", {"parallelism": 3, "rate": 20, "period": 120}, ) # Check pinned status info = client.flow_control.get("USER_GIVEN_KEY") print(info.is_pinned_parallelism) # True print(info.is_pinned_rate) # True # Unpin specific configs client.flow_control.unpin( "USER_GIVEN_KEY", {"parallelism": True, "rate": True}, ) ``` ```bash # Pin a fixed configuration curl -X POST "https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/pin?parallelism=3&rate=20&period=120" \ -H "Authorization: Bearer " # Unpin specific configs curl -X POST "https://qstash.upstash.io/v2/flowControl/USER_GIVEN_KEY/unpin?parallelism=true&rate=true" \ -H "Authorization: Bearer " ``` -------------------------------- ### Error Handling Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Standard error response format for API requests. ```APIDOC ## Error Response ### Description Standard error format returned for 400 and 404 status codes. ### Response - **error** (string) - Error message ``` -------------------------------- ### Publish with Deduplication ID using TypeScript Source: https://upstash.com/docs/qstash/features/deduplication The QStash client library for TypeScript allows you to pass a `deduplicationId` option when publishing a JSON message. This header is automatically added to 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" }, deduplicationId: "abcdef", }); ``` -------------------------------- ### Pin Flow Control Key Configuration Source: https://upstash.com/docs/qstash/api-reference/flow-control/pin-configuration-for-flow-control-key Use this OpenAPI definition to pin a processing configuration for a specific flow-control key. You can set parallelism, rate, and period values. Pinning resets the current state of the flow-control key. ```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.upstash.io 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 ``` -------------------------------- ### DELETE /v2/queues/{queueName} Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Deletes an existing queue. ```APIDOC ## DELETE /v2/queues/{queueName} ### Description Removes a queue from the system. ### Method DELETE ### Endpoint /v2/queues/{queueName} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to delete. ``` -------------------------------- ### Delete a queue Source: https://upstash.com/docs/qstash/sdks/ts/examples/queues Removes an existing queue from the QStash instance. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const queueName = "upstash-queue"; await client.queue({ queueName: queueName }).delete(); ``` -------------------------------- ### Pin Configuration for Flow Control Key Source: https://upstash.com/docs/qstash/api-reference/flow-control/pin-configuration-for-flow-control-key Pins a processing configuration for a specific flow-control key. This allows you to enforce a fixed configuration, overriding configurations provided by incoming messages. Pinning resets the current state (rate count and period) of the flow-control key. ```APIDOC ## POST /v2/flowControl/{flowControlKey}/pin ### Description Pins a processing configuration for a specific flow-control key. ### Method POST ### Endpoint /v2/flowControl/{flowControlKey}/pin ### Parameters #### Path Parameters - **flowControlKey** (string) - Required - The flow-control key for which the configuration will be pinned. #### Query Parameters - **parallelism** (integer) - Optional - The parallelism value to apply to the flow-control key. - **rate** (integer) - Optional - The rate value to apply to the flow-control key. - **period** (integer) - Optional - The period value to apply to the flow-control key, in seconds. ### Request Example ```json { "parallelism": 10, "rate": 100, "period": 60 } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the flow-control key configuration has been pinned. #### Response Example ```json { "message": "Flow control key configuration pinned successfully." } ``` #### Error Response (400) - **error** (string) - Bad request. Returned when the flow-control key is not provided, or when the parallelism, rate or period values are invalid. #### Response Example ```json { "error": "Invalid input parameters." } ``` ``` -------------------------------- ### Publishing Responses Source: https://upstash.com/docs/qstash/api-reference/messages/enqueue-a-message Details the response schemas for publishing messages to URLs or URL groups. ```APIDOC ## PublishResponse ### Description Response schema returned when publishing a message. ### Response - **messageId** (string) - Unique identifier for the published message or the old message ID if deduplicated - **deduplicated** (boolean) - Whether this message is a duplicate and was not sent to the destination. ## PublishToUrlGroupResponse ### Description Response schema returned when publishing a message to a URL group. ### Response - **messageId** (string) - Unique identifier for the published message or the old message ID if deduplicated - **deduplicated** (boolean) - Whether this message is a duplicate and was not sent to the destination. - **url** (string) - Destination URL of the URL Group endpoint. ``` -------------------------------- ### Submit Feedback API Source: https://upstash.com/docs/qstash/api-reference/dlq/delete-a-dlq-message Endpoint for submitting feedback regarding documentation issues. ```APIDOC ## POST /docs/_mintlify/feedback/upstash/agent-feedback ### Description Submit feedback if you encounter incorrect, outdated, or confusing documentation. ### Method POST ### Endpoint https://upstash.com/docs/_mintlify/feedback/upstash/agent-feedback ### Request Body - **path** (string) - Required - The current page path. - **feedback** (string) - Required - Description of the issue. ### Request Example { "path": "/current-page-path", "feedback": "Description of the issue" } ``` -------------------------------- ### Fetch Logs by Message IDs Source: https://upstash.com/docs/qstash/sdks/ts/examples/logs Retrieve logs associated with specific message IDs. This allows for targeted fetching of log entries. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.logs({ messageIds: ["msg-id-1", "msg-id-2"] }); ``` -------------------------------- ### Delete a queue via OpenAPI Source: https://upstash.com/docs/qstash/api-reference/queues/delete-a-queue Defines the DELETE endpoint for removing a queue by its name in 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.upstash.io 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}: delete: tags: - Queues summary: Delete a queue description: Deletes a queue parameters: - name: queueName in: path required: true schema: type: string description: The name of the queue to delete. responses: '200': description: Queue deleted successfully 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 ``` -------------------------------- ### Reset Flow Control Rate Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Reset the rate count and end the current rate period for a specific flow control key. This is useful for immediately allowing more messages to pass if the rate limit has been reached. Ensure the QStash client is initialized. ```python from qstash import QStash client = QStash("") # Reset rate count and end the current rate period client.flow_control.reset_rate("USER_GIVEN_KEY") ``` -------------------------------- ### Filter Logs by State and Limit Results Source: https://upstash.com/docs/qstash/sdks/ts/examples/logs Fetch logs filtered by their state (e.g., 'DELIVERED') and limit the number of returned logs. Refer to the API Reference for additional filtering options. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.logs({ count: 50, filter: { state: "DELIVERED", } }); ``` -------------------------------- ### Create or overwrite a schedule with a custom ID Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Assigns a specific ID to a schedule. If the ID is already in use, the existing schedule is replaced. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); await client.schedules.create({ destination: "https://example.com", scheduleId: "USER_PROVIDED_SCHEDULE_ID", cron: "* * * * *", }); ``` -------------------------------- ### POST /publish Source: https://upstash.com/docs/qstash/api-reference/messages/publish-a-message Publishes a message to a destination URL or URL group. Supports redaction of headers and body content. ```APIDOC ## POST /publish ### Description Publishes a raw request message to the specified destination. Supports granular redaction of headers and body content. ### Method POST ### Endpoint /publish ### Parameters #### Request Body - **raw request** (string/object/binary) - Required - The raw request message to be published. ### Response #### Success Response (200) - **messageId** (string) - Unique identifier for the published message. - **deduplicated** (boolean) - Whether the message was a duplicate. - **messages** (array) - List of responses when publishing to a URL group. #### Response Example { "messageId": "msg_12345", "deduplicated": false } ``` -------------------------------- ### Add Helicone Analytics to Anthropic LLM Request Source: https://upstash.com/docs/qstash/integrations/anthropic Include Helicone analytics for usage monitoring by passing your Helicone API key within the `analytics` object when publishing an LLM request to Anthropic via QStash. ```typescript await client.publishJSON({ api: { name: "llm", provider: anthropic({ token: "" }), analytics: { name: "helicone", token: process.env.HELICONE_API_KEY! }, }, body: { model: "claude-3-5-sonnet-20241022", messages: [{ role: "user", content: "Hello!" }] }, callback: "https://example.com/callback", }); ``` -------------------------------- ### POST /v2/dlq/retry/{dlqId} Source: https://upstash.com/docs/qstash/api-reference/dlq/retry-a-dlq-message Retry delivery of a message from the DLQ. This operation creates a new message with the same content and schedules it for delivery, then removes the original message from the DLQ. ```APIDOC ## POST /v2/dlq/retry/{dlqId} ### Description Retry delivery of a message from the DLQ. When a DLQ message is retried, a new message with the same body and headers is created and scheduled for delivery. The original DLQ message is then removed from the DLQ. ### Method POST ### Endpoint /v2/dlq/retry/{dlqId} ### Parameters #### Path Parameters - **dlqId** (string) - Required - The DLQ ID of the message you want to retry. #### Request Body This endpoint does not require a request body. ### Request Example ```json { "example": "No request body needed" } ``` ### Headers - **Upstash-Retries** (integer) - Optional - You can pass configuration headers to override the configuration of the original message. For example, if the retry count of the original message is 5, you can set it to 0 for the retried message by passing `Upstash-Retries: 0` header to this request. ### Response #### Success Response (201) - **messageId** (string) - Unique identifier for the published message or the old message ID if deduplicated. - **deduplicated** (boolean) - Whether this message is a duplicate and was not sent to the destination. #### Response Example ```json { "messageId": "msg_abc123", "deduplicated": false } ``` #### Error Response (404) - **error** (string) - Error message. This is returned if the message is not found in the DLQ. #### Error Response Example ```json { "error": "Message not found in DLQ" } ``` ``` -------------------------------- ### Error Object Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Standard error response format. ```APIDOC ## Error Object ### Fields - **error** (string) - Required - The error message describing the failure. ``` -------------------------------- ### Pause/Resume a schedule Source: https://upstash.com/docs/qstash/sdks/ts/examples/schedules Allows pausing and resuming of a schedule. ```APIDOC ## POST /schedules/{scheduleId}/pause and POST /schedules/{scheduleId}/resume ### Description Provides endpoints to pause and resume a schedule. ### Method POST ### Endpoint - Pause: /schedules/{scheduleId}/pause - Resume: /schedules/{scheduleId}/resume ### Parameters #### Path Parameters - **scheduleId** (string) - Required - The unique identifier of the schedule. ### Request Example (Pause) ```json { "schedule": "my-schedule" } ``` ### Request Example (Resume) ```json { "schedule": "my-schedule" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Schedule my-schedule paused successfully." } ``` ``` -------------------------------- ### Send Batch Chat Completion Requests Source: https://upstash.com/docs/qstash/integrations/llm Perform multiple chat completion requests in a single batch operation. Supported across JavaScript, Python, and cURL. ```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" }, ... ]' ``` -------------------------------- ### Resume Flow Control Key Source: https://upstash.com/docs/qstash/api-reference/flow-control/resume-flow-control-key Resumes the delivery of messages associated with a specific flow-control key. When a flow-control key is resumed, messages associated with that key will begin to be delivered again. ```APIDOC ## POST /v2/flowControl/{flowControlKey}/resume ### Description Resumes the delivery of messages associated with a specific flow-control key. ### Method POST ### Endpoint /v2/flowControl/{flowControlKey}/resume ### Parameters #### Path Parameters - **flowControlKey** (string) - Required - The flow-control key to resume. ### Responses #### Success Response (200) - **message** (string) - The flow-control key has been resumed. #### Error Response (400) - **error** (string) - Bad request. Returned when the flow-control key is not provided. ### Request Example ```json { "flowControlKey": "your_flow_control_key" } ``` ### Response Example (Success) ```json { "message": "Flow control key 'your_flow_control_key' has been resumed." } ``` ### Response Example (Error) ```json { "error": "flowControlKey is required" } ``` ``` -------------------------------- ### Unpin Flow Control Configuration OpenAPI Definition Source: https://upstash.com/docs/qstash/api-reference/flow-control/unpin-configuration-for-flow-control-key The OpenAPI specification for the POST /v2/flowControl/{flowControlKey}/unpin endpoint, including parameters for parallelism and rate configuration unpinning. ```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.upstash.io 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}/unpin: post: tags: - Flow Control summary: Unpin Configuration for Flow Control Key description: Removes the pinned 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 unpinned. - name: parallelism in: query schema: type: boolean default: false description: The flag to indicate whether to unpin the parallelism configuration. - name: rate in: query schema: type: boolean default: false description: The flag to indicate whether to unpin the rate configuration. responses: '200': description: The flow-control key configuration is pinned '400': description: Bad request. Returned when the flow-control key is not provided. 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 ``` -------------------------------- ### Publish to a URL Group Source: https://upstash.com/docs/qstash/sdks/ts/examples/publish Publishes a message to a pre-configured URL group. The response returns an array of message IDs for each endpoint in the group. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "" }); const res = await client.publishJSON({ urlGroup: "my-url-group", body: { hello: "world" }, headers: { "test-header": "test-value" }, delay: "3s", }); // When publishing to a URL Group, the response is an array of messages for each URL in the URL Group console.log(res[0].messageId); ``` -------------------------------- ### POST /v2/batch - Batch Messages Source: https://upstash.com/docs/qstash/api-reference/messages/batch-messages Send multiple messages in a single request to specified destinations. ```APIDOC ## POST /v2/batch ### Description Send multiple messages in a single request. ### Method POST ### Endpoint /v2/batch ### Parameters #### Request Body - **destination** (string) - Required - 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. Note that destination must be publicly accessible over the internet. If you are working with local endpoints, consider using QStash local development server or a public tunnel service. - **body** (string) - Optional - The raw request message passed to the endpoints as is. - **headers** (object) - Optional - HTTP headers of the message. You can pass all the headers supported in the single publish API. - **queue** (string) - Optional - Queue name to enqueue the message to if desired. ### Request Example ```json [ { "destination": "https://example.com/webhook", "body": "Hello World", "headers": { "Content-Type": "text/plain" } }, { "destination": "my-url-group", "body": "Another message", "queue": "my-queue" } ] ``` ### Response #### Success Response (200) - **messageId** (string) - Unique identifier for the published message or the old message ID if deduplicated. - **deduplicated** (boolean) - Whether this message is a duplicate and was not sent to the destination. #### Response Example ```json [ { "messageId": "msg_abc123", "deduplicated": false }, { "messageId": "msg_def456", "deduplicated": true } ] ``` #### Error Response (400) - **error** (string) - Error message ``` -------------------------------- ### Batch response format Source: https://upstash.com/docs/qstash/features/batch The API returns an array of results corresponding to each message in the batch. ```json [ [ { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint1.com" }, { "messageId": "msg_...", "url": "https://myUrlGroup-endpoint2.com" } ], { "messageId": "msg_..." }, { "messageId": "msg_..." } ] ``` -------------------------------- ### Response Object Structure Source: https://upstash.com/docs/qstash/api-reference/dlq/get-a-dlq-message Defines the structure of the response object returned by the API. ```APIDOC ## Response Object ### Fields - **responseHeaders** (array) - The HTTP response headers received from the destination API. - **responseBody** (string) - The body of the response if it is composed of utf8 chars only. - **responseBodyBase64** (string) - The base64 encoded body of the response if the body contains non-utf8 characters. ``` -------------------------------- ### Configure Queue Parallelism Source: https://upstash.com/docs/qstash/features/queues Set the maximum number of concurrent messages a queue can process. This helps manage endpoint load and improve throughput. Note that queue parallelism is being deprecated in favor of the publish API. ```bash curl -XPOST https://qstash.upstash.io/v2/queues/ \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "queueName": "my-queue", "parallelism": 5, }' ``` -------------------------------- ### POST /url_group/upsert_endpoints Source: https://upstash.com/docs/qstash/sdks/py/examples/url-groups Creates or updates a URL group by adding a list of endpoints. ```APIDOC ## POST /url_group/upsert_endpoints ### Description Creates a URL group or updates an existing one by adding the specified endpoints. ### Request Body - **url_group** (string) - Required - The name of the URL group. - **endpoints** (list) - Required - A list of objects containing the 'url' for each endpoint. ``` -------------------------------- ### DELETE /v2/queues/{queueName} Source: https://upstash.com/docs/qstash/api-reference/queues/delete-a-queue Deletes a specific message queue from the QStash service. ```APIDOC ## DELETE /v2/queues/{queueName} ### Description Deletes a queue from the QStash service. ### Method DELETE ### Endpoint /v2/queues/{queueName} ### Parameters #### Path Parameters - **queueName** (string) - Required - The name of the queue to delete. ### Response #### Success Response (200) - Queue deleted successfully ``` -------------------------------- ### Pause and resume flow control Source: https://upstash.com/docs/qstash/sdks/py/examples/flow-control Allows pausing and resuming message delivery for a specific flow control key. ```APIDOC ## Pause and resume flow control ### Description Allows pausing and resuming message delivery for a specific flow control key. ### Method POST ### Endpoint /v1/flowcontrol/{key}/pause /v1/flowcontrol/{key}/resume ### Parameters #### Path Parameters - **key** (string) - Required - The unique identifier for the flow control key. ### Request Body (Pause) This endpoint does not require a request body. ### Request Body (Resume) This endpoint does not require a request body. ### Response #### Success Response (200) Indicates that the operation was successful. The response body is typically empty. #### Response Example (Pause) ```json {} ``` #### Response Example (Resume) ```json {} ``` ``` -------------------------------- ### Publish Message to URL Group using cURL Source: https://upstash.com/docs/qstash/overall/apiexamples Publish a JSON message to a URL Group using cURL. Replace 'XXX' with your authorization token. ```shell curl -XPOST \ -H 'Authorization: Bearer XXX' \ -H "Content-type: application/json" \ -d '{ "hello": "world" }' \ 'https://qstash.upstash.io/v2/publish/myUrlGroup' ```