Tutorials

How to Auto-Publish Cloudflare Stream Videos with Queues and TypeScript

Cloudflare Stream now delivers video and caption events through Queues. Build a TypeScript publishing pipeline that waits for both video processing and English captions, regardless of event delivery order.

A video finishes processing, and the website makes it available to visitors. The video plays correctly, but there is a small problem: its subtitles are still being generated.

Several minutes later, the captions become available. Until then, the published video is missing something the application considers a requirement.

Waiting a fixed amount of time before publishing might appear to solve this. But how long should the application wait? A short video and an hour-long recording do not necessarily require the same processing time.

On December 3, 2026, Cloudflare introduced support for Stream event subscriptions through Cloudflare Queues. Applications can now receive notifications when individual stages of video processing finish and react to them asynchronously.

In this tutorial, we will build a small publishing pipeline using Cloudflare Workers, Queues, D1, and TypeScript.

A video will become visible on the website only after the application has recorded two conditions:

  • The video is ready to stream.
  • Its English captions are ready.

Neither condition alone is sufficient.

What changed in Cloudflare Stream?

Before this update, applications could receive certain Stream notifications through webhooks or periodically check video information through the API.

Event subscriptions provide another option.

Cloudflare Stream now publishes 14 event types that applications can route to queues. Among them are:

Event Meaning
video_state.ready Video processing completed
video_state.errored Video processing failed
caption.created Caption creation started or a caption was uploaded
caption.ready Captions are available
caption.deleted Captions were removed
download.ready A downloadable video file is available

For our publishing pipeline, we only need video_state.ready and caption.ready.

The difficulty is that Cloudflare Queues does not guarantee delivery order and uses at-least-once delivery. A consumer may therefore process the same event more than once.

Rather than assuming which event arrives first, we will store both readiness conditions independently.

flowchart TD
    A["Cloudflare Stream"] --> B["video_state.ready"]
    A --> C["caption.ready"]
    B --> D["Cloudflare Queue"]
    C --> D
    D --> E["TypeScript Worker"]
    E --> F["Update readiness in D1"]
    F --> G{"Video and English captions ready?"}
    G -->|Yes| H["Publish video"]
    G -->|No| I["Keep unpublished"]

The database remembers what has already happened, even when the events arrive in separate Worker invocations.

1. Create the Worker and queues

For a new project, use Cloudflare’s project generator:

pnpm create cloudflare@latest video-publisher

Choose a TypeScript Worker project. You can also use an existing Worker if your application already has one.

Navigate into the project:

cd video-publisher

Create the queue that will receive Stream events:

pnpm exec wrangler queues create video-publishing

Create another queue for messages that repeatedly fail processing:

pnpm exec wrangler queues create video-publishing-dlq

This second queue is a dead-letter queue. It prevents repeatedly failing messages from simply disappearing after the configured retry limit is reached.

We will connect the Stream event subscription after the database and consumer are ready.

2. Create the D1 database

The Worker needs somewhere to remember the state of each video between events.

Create a D1 database:

pnpm exec wrangler d1 create video-library

Save the database ID returned by Wrangler.

Create a file named schema.sql:

CREATE TABLE IF NOT EXISTS videos (
    id TEXT PRIMARY KEY NOT NULL,

    video_ready INTEGER NOT NULL DEFAULT 0
        CHECK (video_ready IN (0, 1)),

    captions_ready INTEGER NOT NULL DEFAULT 0
        CHECK (captions_ready IN (0, 1)),

    published_at TEXT DEFAULT NULL
);

There is no separate published boolean.

Instead, published_at serves two purposes. It indicates that the video has been published and records when that happened.

An unpublished video might look like this:

id video_ready captions_ready published_at
video-123 1 0 NULL

The video can already be played through Stream, but the application will not include it in its published video library.

3. Configure the Worker

Update your wrangler.jsonc:

{
  "name": "video-publisher",
  "main": "src/index.ts",
  "compatibility_date": "2026-12-04",
  "workers_dev": false,

  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "video-library",
      "database_id": "YOUR_DATABASE_ID"
    }
  ],

  "queues": {
    "consumers": [
      {
        "queue": "video-publishing",
        "max_batch_size": 10,
        "max_batch_timeout": 5,
        "max_retries": 3,
        "dead_letter_queue": "video-publishing-dlq"
      }
    ]
  }
}

Replace YOUR_DATABASE_ID with the actual database identifier.

Apply the schema to the remote database:

pnpm exec wrangler d1 execute video-library --remote --file=schema.sql

Generate TypeScript definitions for the Worker:

pnpm exec wrangler types

The Worker does not need a public HTTP endpoint. Cloudflare Queues invokes its queue() handler directly.

4. Understand the event payloads

The two events identify their videos differently.

A simplified video_state.ready message looks like this:

{
  "type": "cf.stream.video_state.ready",
  "payload": {
    "id": "video-123",
    "readyToStream": true
  }
}

A caption event instead contains videoId:

{
  "type": "cf.stream.caption.ready",
  "payload": {
    "videoId": "video-123",
    "language": "en",
    "status": "ready"
  }
}

The complete messages include additional payload properties, source information, and event metadata.

Notice the distinction between id and videoId. Treating the payloads as identical would leave the Worker searching for the wrong property in one of the events.

There is also no reason to process every caption language. Our publishing policy requires English captions specifically.

Create src/events.ts:

export interface ReadinessUpdate {
  videoId: string;
  videoReady: 0 | 1;
  captionsReady: 0 | 1;
}

function isRecord(
  value: unknown,
): value is Record<string, unknown> {
  return (
    typeof value === "object" &&
    value !== null &&
    !Array.isArray(value)
  );
}

function isId(value: unknown): value is string {
  return (
    typeof value === "string" &&
    value.trim().length > 0
  );
}

export function parseEvent(
  event: unknown,
): ReadinessUpdate | null {
  if (
    !isRecord(event) ||
    !isRecord(event.payload)
  ) {
    throw new Error("Invalid Stream event");
  }

  const { type, payload } = event;

  switch (type) {
    case "cf.stream.video_state.ready": {
      if (!isId(payload.id)) {
        throw new Error("Missing video ID");
      }

      return {
        videoId: payload.id,
        videoReady: 1,
        captionsReady: 0,
      };
    }

    case "cf.stream.caption.ready": {
      if (
        !isId(payload.videoId) ||
        typeof payload.language !== "string"
      ) {
        throw new Error("Invalid caption payload");
      }

      if (payload.language !== "en") {
        return null;
      }

      return {
        videoId: payload.videoId,
        videoReady: 0,
        captionsReady: 1,
      };
    }

    default:
      return null;
  }
}

The parser accepts unknown because TypeScript interfaces cannot validate incoming JSON at runtime.

An unsupported event returns null. A malformed event throws an error.

Most importantly, both supported events are converted into the same internal structure. The database no longer needs to know which particular Stream payload produced the update.

5. Update readiness and publish atomically

We could write two separate database operations: one to update the readiness flags and another to publish the video.

But consider what happens if the Worker stops between those operations.

The readiness flags may already indicate that everything is complete, while the video remains unpublished.

A retry could recover that state, but there is no need to introduce the intermediate state in the first place.

Both operations can be combined into a single SQL statement.

Create src/index.ts:

import { parseEvent } from "./events";

interface Env {
  DB: D1Database;
}

const UPDATE_VIDEO = `
  UPDATE videos
  SET
    video_ready = MAX(video_ready, ?1),
    captions_ready = MAX(captions_ready, ?2),

    published_at = CASE
      WHEN MAX(video_ready, ?1) = 1
        AND MAX(captions_ready, ?2) = 1
      THEN COALESCE(
        published_at,
        CURRENT_TIMESTAMP
      )
      ELSE published_at
    END

  WHERE id = ?3
`;

export default {
  async queue(batch, env): Promise<void> {
    for (const message of batch.messages) {
      try {
        const update = parseEvent(message.body);

        if (!update) {
          message.ack();
          continue;
        }

        const result = await env.DB
          .prepare(UPDATE_VIDEO)
          .bind(
            update.videoReady,
            update.captionsReady,
            update.videoId,
          )
          .run();

        if (!result.success) {
          throw new Error("Database update failed");
        }

        if (result.meta.changes === 0) {
          console.info(
            "Unregistered video:",
            update.videoId,
          );
        }

        message.ack();
      } catch (error) {
        console.error(
          "Stream event processing failed",
          message.id,
          error,
        );

        message.retry({
          delaySeconds: 30,
        });
      }
    }
  },
} satisfies ExportedHandler<Env, unknown>;

Two SQL functions deserve attention here.

The first is MAX():

MAX(video_ready, ?1)

Suppose the database already contains video_ready = 1. A caption event arrives carrying videoReady: 0.

Assigning the incoming value directly would incorrectly reset the video’s readiness.

MAX(1, 0) preserves the existing state.

The second function is COALESCE():

COALESCE(published_at, CURRENT_TIMESTAMP)

When the publication timestamp is missing, it assigns the current time. When the video has already been published, it preserves the original timestamp.

Repeated events therefore do not continuously change the publication date.

The readiness flags and publication timestamp are updated together, in one database statement.

6. Deploy the Worker and subscribe to Stream

Deploy the consumer:

pnpm exec wrangler deploy

Now create the event subscription:

pnpm exec wrangler queues subscription create video-publishing --source stream --events video_state.ready,caption.ready

The subscription uses the short event names, while the messages delivered to the consumer contain their fully qualified names, such as cf.stream.caption.ready.

You can inspect Worker activity using:

pnpm exec wrangler tail video-publisher

At this point, Stream can send the selected events to the queue, and the Worker can process them through D1.

But the database still needs to know which videos belong to the application.

7. Register a video before processing begins

Stream subscriptions operate at the account level. A queue can receive events concerning videos from other applications sharing the same Cloudflare account.

Automatically inserting and publishing every received video would be a poor default.

Instead, register the video explicitly:

INSERT INTO videos (id)
VALUES ('YOUR_STREAM_VIDEO_ID')
ON CONFLICT(id) DO NOTHING;

The publishing Worker only updates existing rows.

For a real upload system, Cloudflare’s Direct Creator Upload API is useful because it returns a video identifier and an upload URL before the file is uploaded.

Your application can register that identifier in D1 before giving the uploader access to the URL.

This avoids a race in which the video finishes processing before its database record exists.

If you register videos only after uploading them, you should also reconcile their current status through the Stream API. An event received before registration may have already been acknowledged and will not automatically be replayed.

8. Generate or upload English captions

Subscribing to caption.ready does not generate captions.

It only informs the application when captions become available.

For a simple end-to-end test, upload a video and request English captions through the Stream Dashboard or API.

Cloudflare provides the following endpoint for generating captions:

POST /accounts/{account_id}/stream/{video_id}/captions/en/generate

For example:

curl -X POST \
  "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/stream/$VIDEO_ID/captions/en/generate" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

The variables represent your own account, video, and appropriately scoped API token.

Cloudflare requires the video to be ready before AI caption generation can begin.

That establishes an order in which the underlying processing happens, but not necessarily the order in which our queue consumer receives its notifications.

Caption generation could also be initiated automatically from a separate Worker. This tutorial deliberately leaves that operation outside the publishing consumer, since retrying a caption-generation request introduces its own idempotency concerns.

9. Test event ordering and duplicate delivery

The publishing logic should work even if notifications arrive in an unexpected order.

For example, consider the following sequences:

Received events Published?
Video ready No
Captions ready No
Video ready, captions ready Yes
Captions ready, video ready Yes
Video ready, video ready No
Both ready, followed by duplicates Yes, original timestamp preserved
Video ready, German captions ready No

The SQL statement was checked separately using an in-memory SQLite database. Both event orders produced the expected publication state, and duplicate updates preserved the original timestamp.

The full Cloudflare deployment was not independently executed.

To inspect the state of a real video after deploying your Worker, run:

pnpm exec wrangler d1 execute video-library --remote --command="SELECT * FROM videos"

After the first readiness event, one flag should be set to 1, while published_at remains NULL.

After the second, both flags should be 1, and the publication timestamp should exist.

10. Display published videos on your website

Once the database controls publication, the public-facing application can retrieve its video library using a simple query:

SELECT id, published_at
FROM videos
WHERE published_at IS NOT NULL
ORDER BY published_at DESC;

The application no longer needs to ask Cloudflare Stream about processing progress every time someone opens the video library.

It reads the publication state maintained by the event consumer.

However, hiding a video from this query does not make the underlying Stream video private.

If someone already knows its playback URL, they may still be able to access it.

For videos that must remain inaccessible before publication, configure Stream to require signed URLs and only issue playback tokens after checking the application’s publication state and access rules.

What happens when something fails?

Suppose D1 is temporarily unavailable when a caption notification arrives.

The Worker catches the failure and requests another delivery after 30 seconds.

If processing continues to fail beyond the configured retry limit, the message moves to video-publishing-dlq.

Messages in that queue still require inspection and, when appropriate, reprocessing. A dead-letter queue does not resolve the underlying failure automatically.

There is another limitation to our implementation.

The readiness flags only move from 0 to 1. This is appropriate for a one-time publication pipeline where the video and its captions are not subsequently replaced or deleted.

If an editor deletes the English caption track after publication, the database will not notice because we did not subscribe to caption.deleted.

For applications with editable video libraries, additional events and reconciliation with the Stream API are necessary. Since event delivery can be reordered, simply resetting flags whenever a deletion or update notification arrives may also be insufficient.

The current state of the resource matters, particularly when publication must be revoked.

The December 3 update gives applications a more direct way to react to Stream processing events.

But Cloudflare still does not determine when a video is ready for your particular website. Its processing system knows whether the video can be streamed and whether a caption track exists.

The application decides whether those conditions are sufficient for publication.

In our example, that decision is recorded in D1, independently of event arrival order, repeated delivery, and individual Worker invocations.

External Sources used for this article

Related Articles

View all →