Search code examples
cloudflare-workersserverless-architecture

How does cloudflare workers support websockets but not Raw TCP?


Recently i came across serverless databse and serverless backend and i was using cloudflare worker for making my backend with NeonDB .what confuses me is why serverless backend doesnt allow TCP connection but allows websockets from what i know websockets use TCP.

Also,one more doubt how a serverless backend will interact with serverfull DB The statement that caused confusion was this one

But there’s a problem. PostgreSQL connections are made over TCP. And modern serverless platforms like Cloudflare Workers or Vercel Edge Functions — based on V8 isolates — generally don’t talk TCP. So until now, you had an unfortunate choice. Serverless database or serverless compute: pick any one. source (https://neon.tech/blog/serverless-driver-for-postgres)

Please keep answers a little easy considering i am a beginner

Confusion on a theory topic


Solution

  • The text you quoted is outdated. Cloudflare Workers have supported outgoing TCP connections for almost a year now: https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/

    As of this writing, Workers still does not support receiving incoming TCP connections, only making outgoing connections. But incoming connections are likely to be supported in the future.

    why serverless backend doesnt allow TCP connection but allows websockets from what i know websockets use TCP.

    HTTP also uses TCP, so you could similarly ask: Why is HTTP allowed but not TCP? Cloudflare Workers supported HTTP (both incoming and outgoing) from the beginning, but still doesn't support incoming TCP today. Why is that?

    The main challenge here is routing. HTTP requests are routed based on a URL. TCP connections, meanwhile, our routed strictly based on IP address. Cloudflare does not give each worker its own IP address. There just aren't enough IP addresses to go around. So, many hostnames share the same address. When an HTTP request arrives, Cloudflare reconstructs the URL being requested based on the Host header and the request path, and then can determine from there which web site is being requested and which Worker should run, if any. When a TCP connection arrives, though, Cloudflare only knows what IP address the connection was trying to connect to. In order to allow Workers to receive TCP connections, then, we seemingly would need to give every Worker its own IP address, but that would be extremely expensive.

    Note that, in this respect, WebSockets are very different from plain TCP sockets. A WebSocket is initiated as an HTTP request, with a URL. It can be routed just like any HTTP request. That's why Workers are able to support WebSockets easily.