BuildRiot
Sign in

Article · Backend

Build and test bidirectional gRPC on Cloudflare’s inbound TCP beta

Cloudflare’s public beta lets Spectrum accept TCP connections and route them through a Worker and Durable Object to a gRPC server in a container. This guide explains eligibility, follows the official streaming example and outlines tests for slow readers, interrupted connections and container replacement.

Blue and teal ribbons weave from a miniature laptop through a gateway and processing stations to a container, with a clamp, a broken connection, and a replacement container illustrating streaming tests.
Illustration: BuildRiot (AI-generated)

Key takeaway

The beta provides an ingress path for bidirectional gRPC, while application code still controls buffering, recovery and shutdown. Developers should test those behaviors before relying on long-running streams.

A TCP route to a streaming server

Cloudflare opened inbound TCP for Workers and bidirectional gRPC in Containers to public beta on November 19, 2026. Connections pass through Spectrum, a Worker and a Durable Object before reaching the container’s gRPC server. The demonstration server greets clients, echoes messages and sends a final response after the client finishes sending. That establishes a useful baseline for testing longer streams and interrupted connections. Sources: Cloudflare

The Worker forwards raw TCP without parsing HTTP/2 or gRPC. In the example, the container handles Transport Layer Security (TLS), HTTP/2 and gRPC while the proxies forward encrypted bytes. Both proxy stages await their upstream connection, forward data concurrently in both directions and close sockets during cleanup. They also preserve TCP half-closes, allowing one side to stop sending while still receiving data. Sources: Cloudflare

Check eligibility before building

Check the account requirements in the table below before implementing the service. Spectrum’s Worker-origin route supports Pro and Business zones, plus zones with Spectrum Enterprise enabled. Free zones are unsupported. An Enterprise zone subscription alone does not provide Spectrum Enterprise access. Containers require Workers Paid, and Workers usage is billed separately from Spectrum. Sources: Cloudflare

Table

Spectrum Worker-origin prerequisites and restrictions

RequirementDocumented position
ZonePro, Business or Spectrum Enterprise; no Free zones
ContainersWorkers Paid required
Without Spectrum EnterpriseOne Worker-origin application per zone, one TCP port
Account and DNSWorker and zone share an account; Cloudflare is authoritative
Origin identityImmutable 32-character Worker tag, not its name
Routing configurationWorker traffic type; no port ranges
Unsupported fieldsDirect/DNS origins, origin port, virtual network ID, Proxy Protocol, Argo Smart Routing
Check these routing requirements before configuring the streaming service.Sources: Cloudflare

Use backend TLS for the passthrough example. Inbound Spectrum sockets cannot upgrade to TLS through the socket API. Configurations without Spectrum Enterprise must omit the TLS configuration field. Spectrum Enterprise also supports flexible TLS termination with an advanced or custom certificate; Universal SSL is unsupported for that mode. For the initial deployment, follow the example’s client behavior: validate the container’s certificate and negotiate HTTP/2. Sources: Cloudflare

Deploy the official streaming baseline

Begin with Cloudflare’s complete example, which defines ByteStream.Chat with streaming ByteChunk requests and responses carrying byte payloads. It uses @grpc/grpc-js version ^1.14.7, @grpc/proto-loader version ^0.8.1, Docker and cloudflare.config.ts. Certificate and key bindings come from Secrets Store. Initialize the project with the command below, then follow the example’s server, proxy and certificate configuration. Sources: Cloudflare

cf init

The Worker routes to a named Durable Object, which connects to container port 50051. Await the complete forwarding operation because settling the connect handler’s returned promise closes the inbound socket. Process startup and service readiness are separate: the Containers overview polls a health endpoint before forwarding requests. The gRPC example waits three seconds, then allows up to 20 connection attempts with 100-millisecond timing constants. Treat those values as example settings, not startup guarantees. Sources: Cloudflare

For local testing, use the listener configuration below; exporting the connect handler alone does not create a listener. Point the client at localhost:8788. Local Secrets Store values require Wrangler even though the example otherwise uses cf. A successful local test checks the application path; test public Spectrum routing separately. Sources: Cloudflare

{
  "connect": [
    { "protocol": "tcp", "port": 8788 }
  ]
}

Deploy with the command below; provisioning can take minutes. Configure Spectrum for TCP port 50051 and the chosen hostname. Use the immutable Worker tag as the origin identifier. Connect the TLS client to that hostname, validate its certificate and negotiate HTTP/2. Sending an HTTP tunnel request to the Worker’s public HTTP URL does not invoke the TCP handler. After rotating certificate secrets, restart existing containers because their startup environment retains the previous values. Sources: Cloudflare

cf deploy

Make backpressure visible

Before load testing, consider adding a session identifier, sequence number, acknowledged sequence and server build identifier to the experimental protocol. These proposed fields help expose gaps, duplicates and version changes. Start with a single named instance, then repeat across multiple names. Naming a Durable Object does not establish fleet autoscaling. Cloudflare’s FAQ says built-in stateless autoscaling is unavailable and suggests random selection from a fixed pool. Sources: Cloudflare

Node’s stream documentation tells producers to stop when a write returns false and wait for the drain event before continuing. The announcement’s echo handler does not check that return value. It therefore does not demonstrate bounded buffering under a slow reader. That omission is not evidence of a Cloudflare transport defect. The gRPC flow-control guide warns that manual flow control can deadlock when both peers write extensively without reading. Keep the normal test client reading responses while it sends requests. Sources: Cloudflare, Node.js, gRPC

  1. Set a memory budget and choose a range of payload sizes and concurrent stream counts.
  2. Establish normal-consumer behavior, then pause response consumption while requests continue.
  3. Reverse the experiment by slowing server request consumption.
  4. Record resident memory, queue depth, write backpressure, drain wait time, throughput and recovery time.
  5. Compare the original handler with bounded queues and backpressure handling, including cancellation while a producer waits.
  6. Repeat with streams sharing a channel and with separate channels.

Judge success by bounded memory, controlled producer slowdown and recovery when reading resumes. Check that cancellation releases waiting producers and associated state. Treat the selected workloads as test conditions, not published platform capacity.

Separate stream completion from connection recovery

Exercise the interruption cases in the table below separately. Normal request completion should still allow the final response demonstrated by Cloudflare’s server. Use a separate TCP probe for transport half-closes. Ending the request side of a gRPC call alone does not establish a TCP half-close through every proxy. Sources: Cloudflare

Table

Proposed interruption tests and evidence

TestProcedureEvidence
Normal completionStop sending; continue readingFinal response, status, acknowledged sequence
TCP half-closeSeparate probe closes only its write directionReverse-direction bytes
Abrupt lossReset during a message sequenceClient status, cancellation, cleanup latency
Silent failureDrop packets without a resetDetection time under client deadlines
RecoveryRestore connectivity; create a new remote procedure callReconnect time, gaps, duplicates, resume behavior
Process failureTerminate the active serverOutstanding messages, replacement readiness
Each proposed test examines a different part of connection handling or application recovery.

Define acknowledgement and replay rules before judging recovery. A restored channel alone does not prove that the interrupted application session resumed correctly. Compare acknowledged sequences across the failure to identify gaps and duplicates. If the application promises persistence, verify accepted messages against durable records.

Test replacement before trusting long streams

Investigate deployment order and version compatibility before relying on long streams. Check whether new Worker code can reach an older container image and what deployment success means for container readiness. Establish how rollout settings affect replacement and whether any grace period applies to connections or individual streams.

Keep streams open before deployment, immediately before replacement and during startup, then deploy an image with a different build identifier. Separately test a Worker-only change. Record any signals received, last acknowledgement, remote procedure call status, instance identity and recovery latency. Measure how long the process has to exit and test its shutdown handling. Verify which recovery data survives replacement and whether the application needs external storage.

No reproducible benchmark establishes latency or throughput improvements for this November ingress path, and the tests described here are proposals, not measured results. Maximum connection duration, idle timeouts, connection quotas, live-socket behavior during Worker updates or Durable Object eviction, and complete billing remain open questions. Before setting service targets, compare the same image and TLS configuration directly and through Cloudflare. Measure connection-to-first-response time separately from steady-state round-trip time, recording client location, instance size, deadlines, channel count and warm or cold state. Report latency distributions, throughput, failures and sample counts, then assess recovery against the application’s target.

Attribution

Sources

  1. 1CloudflareInbound TCP and gRPC for Workers and Containers now in public betaSource published (UTC)
  2. 2CloudflareRoute TCP traffic to a Worker
  3. 3CloudflareBidirectional gRPC with Workers and Containers
  4. 4CloudflareConnect handler
  5. 5CloudflareOverview · Cloudflare Containers docs
  6. 6CloudflareLocal development
  7. 7CloudflareProtocols
  8. 8CloudflareFrequently Asked Questions
  9. 9Node.jsStream | Node.js v24.15.0 Documentation
  10. 10gRPCFlow Control

Read the original source for full details and context.

Report a problem

Links, dates or what you expected. Do not include passwords or private data.

More on Backend

All Backend stories

Review · Backend

Review: PostgreSQL 19, a relational database with new maintenance controls

PostgreSQL 19 adds concurrent table repacking that permits access during most of the work. The PostgreSQL Global Development Group released this version of its open-source relational database on November 19, 2026. According to the project, pg_plan_advice influences planner choices, while pg_stash_advice stores and applies guidance by query identifier. The release also adds logical replication of sequence values, get-or-create operations and JSON export.

PostgreSQL

Review · Frontend

Review: MoonBit 1.0 release candidate, a language for WebAssembly and native apps

MoonBit released its 1.0 release candidate on November 26, 2026, freezing compiler changes to bug fixes until 1.0. Its primary targets are native code and WebAssembly, with JavaScript support for browsers and interfaces. The team targets February 18, 2027, for the full release with a stable core library. The async and archive packages may still receive minor API refinements. The moon fix command can apply compiler-suggested fixes.

MoonBit

Build and test bidirectional gRPC on Cloudflare’s inbound TCP beta · BuildRiot