9 ms·
Connect() – a new API for creating TCP sockets from Cloudflare Workers
- rockwotj 3y agoOriginal article: https://blog.cloudflare.com/workers-tcp-socket-api-connect-databases/ https://blog.cloudflare.com/workers-tcp-socket-api-connect-d...
- DylanSp 3y agoSeems like this should be what's linked to, especially since it's got a code example that actually directly uses the connect() API.
- dang 3y agoThanks! We've changed to that from https://www.infoq.com/news/2023/05/cloudflare-workers-connect-api/ https://www.infoq.com/news/2023/05/cloudflare-workers-connec....
- say_it_as_it_is 3y agoWhat were Workers offering until now without basic tcp network io?
- yangcheng 3y agohttp requests, js execution and a kv store. Actually very useful. You can run many stuffs there from simple webhooks to full CMS
- mindwok 3y agoI haven't used Workers, but from the article it seems that they were limited to the standard APIs available across browsers and JS runtimes like Express and Deno, so you could use the fetch API or AJAX for things like HTTP, but there was no standard for raw TCP sockets they could use.
- re-thc 3y agoTcp is a last resort rather than an important feature. Most tcp connection are built stateful. They expect long running rather than short-style connections like http. It'd be very expensive running serverless tcp connections e.g. to a database.
- ZiiS 3y agoYou could do http just not other TCP protocols.
- jakear 3y agoStatic file serving, HTTP requests, eventually-consistent Key-Val store, and a funky sort of way to able to edit/view consistent data from a single location, but only if you pay minimum $5 month (anyone out there like Durable Objects?).
- crabmusket 3y agoI'm currently building a real-time multiplayer editor on durable objects and I love them. I wish other cloud providers would ruthlessly copy them so I don't have that vendor lock-in feeling.
- jakear 3y agoAre you bothered by how they only stay alive for 60s or so before being killed? Or the somewhat difficult to estimate pricing? I eventually just decided for those use cases I'd rather run a dedicated server. Pricing is easier, no lock in, and it doesn't die on me unexpectedly.
- crabmusket 3y agoThey usually stay alive while they're receiving requests and die after a period of inactivity - though they can also die unexpectedly for other reasons. This necessitates some more careful design - clients must assume the server can go away at any time and therefore work in a local-first fashion. I was interested in doing that anyway, so it didn't feel like an imposition. I think the core of what I really like about DO's is that it's a single thread with a globally unique and accessible address.
- jakear 3y agoI agree the value proposition is compelling. Another annoyance is how little it gels with the rest of Pages. I'd expect that if I'm developing an application from the ground up in Pages, incorporating the various Cloudflare value-ads should come relatively naturally. Instead I need to have entirely separate projects just for these components.
- sammy2255 3y agoThats cool, do they let you fetch the current datetime multiple times now? Last time I remember you could get the current instant but it would never change for the whole request due to “security reasons”
- tyingq 3y agoThey are using V8 isolates, so spectre-like timing attacks are a legitimate concern. See https://leaky.page/ https://leaky.page/ for an example. Their explanation: "the time value returned is not the current time. Date.now() returns the time of the last I/O. It does not advance during code execution" https://developers.cloudflare.com/workers/learning/security-model/#step-1-disallow-timers-and-multi-threading https://developers.cloudflare.com/workers/learning/security-...
- vlovich123 3y agoIt changes across IO boundaries. It stays fixed otherwise because Spectre is a problem because all isolates run within the same process.
- blibble 3y agonow we can create a 1986 style berkeley socket, woohoo
- tyingq 3y agoWell, from ~275 globally distributed locations, with a decent free tier. I'm sure there's some interesting things you could do.
- goodpoint 3y ago...all entirely controlled by a single company. Running on a proprietary closed source stack. Pass.
- dom96 3y agoA significant chunk of it is open source: https://github.com/cloudflare/workerd/ https://github.com/cloudflare/workerd/
- tyingq 3y agoWell, it's javascript at the edge. Porting it to somebody else's "javascript at the edge" apis for sockets, kv store, etc, wouldn't be that hard. The lock-in doesn't seem that strong to me. And fully open source DIY global edge seems hard outside of maybe running a botnet :)
- harrylepotter 3y agoI wouldn’t underestimate that. All CDN vendors are substantially different. Lambda @edge is broken into requests and responses, and don’t even get me started on Akamai.
- crabmusket 3y agoIt's nice that CloudFlare workers use the service worker API... But useless unless other cloud providers also get on the standards bandwagon -_-
- arek_nawo 3y agoCF Workers seem to slowly becoming a full-blown "edge" platform. A year or two ago you couldn't really use it for much except simple cloud functions and key-value storage, but now, with WS support, S3 storage and SQL database coming along I'll be taking a second look.
- xwdv 3y agoNot sure why this is a surprise to people, AWS started with similar humble origins. The goal of Cloudflare has been to become the fourth public cloud for a long time now, I think in several years they will be the most powerful platform to build on.
- arek_nawo 3y agoNot really a surprise, and the platform will very likely grow further, though I wouldn't compare CF to AWS in anything except the rise in popularity. I'd say they're "reinventing" cloud in a way. From my point of view, AWS is (mostly) IaaS, likes of Heroku - PaaS, whereas CF Workers and their "ecosystem" is primarly serverless, though - with these recent additions - they're expanding what this category of tools can do. It's a unique platform for sure.
- xwdv 3y agoYes it will be better than AWS.
- eropple 3y agoI used to work at Render, and I said often "Cloudflare is the iceberg - only ten percent of it is above the water and it's going to tear a big chunk out of the [PaaS] boat". Over time it seems more and more confirmable as a hypothesis.
- arek_nawo 3y agoTrue. I was actually looking at Render a while back to host my app. The Render Disks were the one feature I was most interested in, as no other PaaS provider I was aware of provided persistent disk storage. The prices were a bit too much for a side-project though, and with no managed MongoDB, I ultimately made the app not require the disk storage and moved to Railway.
- tyingq 3y agoMakes me curious how they track abuse. Since it's distributed pretty widely, it seems like it could make a pretty good free portscanner, command-and-control network, DDOS amplifier, etc, with a group of free-level accounts.
- sparrish 3y agoNearly 90% of HTTP attacks on our website come from Cloudflare Workers. We've chosen to block huge subnets of their IPs because of it. This new raw TCP connection feature will undoubtedly be used to attack other services in similar ways.
- spacetime_cmplx 3y agoThat's concerning. Could you elaborate on how you identified the traffic as cloudflare workers? Also, what sorts of HTTP attacks? wp-admin probes? Plain DDoS? Cloudflare has (had?) a murky history with not taking down DDoS for hire services ironically hosted behind cloudflare. But while you could argue they had an incentive to do that (sell protection), I can't think of any incentive to let Workers be abused.
- capableweb 3y ago> Could you elaborate on how you identified the traffic as cloudflare workers? Trivial based on the fact that HTTP requests coming from CloudFlare Workers has a cf-worker header. Also, any traffic coming from cloudflare-owned IP blocks clearly belongs to cloudflare and can be safely blocked.
- InvaderFizz 3y agoOn the second point, with the introduction of Cloudflare WARP VPN, that's not quite true. Additionally, I believe Safari Private Relay may end up looking like it originates from CF as well.
- 3y ago
- MrDOS 3y agoNice to see Workers steadily reinventing CGI-served PHP. Maybe in another few years they'll reinvent mod_php, too, and then we can have persistent connections!
- danwee 3y agoI don't understand something: "Cloudflare workers" are, at the end of the day, computers, right? Probably virtual ones (either VMs or containers). So, why is the ability of creating TCP sockets a feature? Why their "cloudflare workers" had that handicap to begin with?
- paulgb 3y agoThey are neither VMs or containers, but V8 Isolates. They lacked an API for making outgoing raw TCP connections in the same way that JavaScript running in a browser can’t.
- poxrud 3y agoThis used to be an option in Chrome when running in an extension. Sadly sockets were removed in manifest v3.
- silentsea90 3y agoI was lost about the distinction. This talk really helped: https://www.infoq.com/presentations/cloudflare-v8/ https://www.infoq.com/presentations/cloudflare-v8/
- zuprau 3y agoI might be wrong, but they're more like a browser’s "service worker" than a Node app.[0] The fact that they have to manually add "compatibility" with Node modules like `utils`[1] seems to support this. [0]: https://blog.cloudflare.com/node-js-support-cloudflare-workers/#supporting-native-apis https://blog.cloudflare.com/node-js-support-cloudflare-worke... [1]: https://blog.cloudflare.com/workers-node-js-asynclocalstorage/ https://blog.cloudflare.com/workers-node-js-asynclocalstorag...
- crabmusket 3y agoThat's exactly right, and they even use the same API[1] for accepting and replying to HTTP requests . As well as supporting other service worker APIs like caches. [1] https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent
- mobb_solo 3y ago>the connect() function returns a TCP socket that allows developers to read and write data until the connection remains open. I sorta stopped caring about grammatical errors since I realized English is but a second language to many people. I wonder of The Editor has regretfully gone the way of the dodo in 'technical' writing..
- okwubodu 3y ago> I wonder of if*
- sanitycheck 3y agoRegardless of English communication ability, we should hope programmers understand the difference between "until" and "while". (VB, bash, certainly others.)
- hankchinaski 3y agoLooking forward to when we are going to be able to listen to incoming tcp connections also. It will become a fully blown platform. The developer experience with wrangler is still off though
- jakear 3y agoRight? They pretend to have a dev server with live reload, but it's about the worst implementation of such I've seen. Protip is to wrap it within some watchers and cleaners of your own: while true; do pkill -f miniflare-dist; npx wrangler pages dev public; done; Lest ye end up with a million rogue processes spinning down your CPU after each file saved with a syntax error causes the entire dev launcher to crash and leave its spawn everywhere...
- paulgb 3y agoI’m curious what use case you have in mind for this?
- hankchinaski 3y agoSmtp server or another case is creating honeypots servers
- AtNightWeCode 3y agoNot the author but to use WAF rules that can be used on layer 4 for instance. Zone lockdown, some rate limits...
- r3trohack3r 3y agoA serverless IRC server. With a TCP bridge it seems like you can already do a serverless IRC webclient bridging an IRC connection to a websocket.
- galactus 3y agoConcerning the use of this for regular DB connections.. isn't there a bit of a conflict between edge computing, which runs close to the user, and using a regular centralized DB, which resides in a fixed region?
- dknecht 3y agoWith a recent announcement we are addressing this by dynamically moving the code to be close to the data when appropriate - https://blog.cloudflare.com/announcing-workers-smart-placement/ https://blog.cloudflare.com/announcing-workers-smart-placeme...
- slashdev 3y agoThat's really interesting. Between this and TCP sockets you could now design really interesting distributed, stateful services on Cloudflare Workers. I'd love to design a database for this environment (if you're reading this at Cloudflare, you can hire me to work on this.) I think something that distinguishes between write and read requests, moves writes close to the leader server hosting the data being written, handles reads at the edge, and replicates the deterministic request itself would perform the best and give sequential consistency. This is the approach taken by fauna.com, and it's competitive with Spanner but without the need for GPS and atomic clocks to provide an accurate time source.
- Havoc 3y agoAnybody know if the API also works with rust wasm workers?
- dom96 3y agoNot yet, but we're working on that https://github.com/cloudflare/workers-rs/pull/324 https://github.com/cloudflare/workers-rs/pull/324
- epolanski 3y agoI really like Cloudflare's offerings, they are top notch in areas like security, performance and pricing. What I'm not fond of is company's fixation only with big clients and leaving out a serious effort to bring on the average solo programmers/entrepeneurs (something on which companies like Stripe instead thrived on). Cloudflare really needs to do more to target small fishes, they are tomorrow mid and big fishes trying to understand how to make small and medium problems trivial leveraging their platforms.
- hughw 3y agoMy experience is the opposite. It's quite easy and cheap to start using CF, starting with free plans for their proxy. We've added other CF services and pay them now, I think, about $25/month. Very accessible.
- da02 3y agoWhich paid CF services do you use?
- AtNightWeCode 3y agoThe opposite. I always add CF to small sites.
- epolanski 3y agoMy main gripe was with all the offerings beyond the trivial Firewall/CDN/storage/lambda use cases.
- AtNightWeCode 3y ago"It is an enterprise feature but not including in your enterprise agreement." "You want to use XYZ? Fine, we include any count of XYZ for free. Next agreement negotiation. 200$ for each instance of XYZ." CF is simply not the service to use for any large site.
- supriyo-biswas 3y ago
- bob1029 3y agoI've got a use case that is now almost entirely covered by these workers but the JS-only API is somewhat painful from my perspective. If CF offered support for running x64 linux .NET6+ binaries on these edge workers, I'd probably block off the next 3-4 weekends to play around with the stack. I realize this is probably untenable considering certain compromises made in the CF infra (i.e. V8 optimizations), but one can dream. For now, Azure appears to be my prison.
- ignoramous 3y ago> If CF offered support for running x64 linux .NET6+ binaries on these edge workers... Cloudflare has teased about containers in the recent past (but not quite running them on the edge, as it were): https://blog.cloudflare.com/containers-on-the-edge/ https://blog.cloudflare.com/containers-on-the-edge/ I believe, their very new Browser Rendering service is an example of one such deployment? https://blog.cloudflare.com/browser-rendering-open-beta/ https://blog.cloudflare.com/browser-rendering-open-beta/
- kentonv 3y ago> If CF offered support for running x64 linux .NET6+ binaries on these edge workers, I'd probably block off the next 3-4 weekends to play around with the stack. The trouble with "containers on the edge" is that if we just literally put your container in 300+ locations it's going to be quite expensive. Cloudflare Workers today actually runs your Worker in 300+ locations, and manages to be cost effective at that because it's based on isolates rather than containers. We'll probably offer some sort of containers eventually, but it probably won't be oriented around trying to run your container in every location. Instead I'm imagining containers would come into play specifically for running batch jobs or back-end infrastructure that's OK to concentrate in fewer locations. (I'm the tech lead for Workers.)
- bob1029 3y agoThank you for taking time to reply. What does the roadmap look like around establishing some sort of multi-tier architecture within the CF product stack? I imagine I could hack something together today by combining CF workers and another hyperscaler to run my .NET workload (TCP connection definitely helps with this!), but I think that there would still be a lot of friction with operations, networking, etc at scale. Ideally, workers and backend would be automagically latency-optimized and scaled relative to each other.
- AtNightWeCode 3y agoSo they added this. But stale-while-revalidate does not work. And there is no request collapsing. And you still have to write code to get CORS to work in workers. And you can't cache the response from workers. How does CF prioritize things? :)
- koolba 3y agoWhat's the source IP for these sockets? Is it consistent across requests? Opening a raw socket from a worker combined with a basic HTTP implementation could let you create a dynamic proxy that uses Cloudflare's worker IP range as the source address. That sounds like a fun^Winteresting way of getting around rate limits. Related, does waiting for I/O count as "cpu time"? A proxy request might 10s of ms in total, but most of that will be waiting for packets to flow back and forth.
- ignoramous 3y ago> Opening a raw socket from a worker combined with a basic HTTP implementation could let you create a dynamic proxy Yep, see: https://github.com/zizifn/edgetunnel https://github.com/zizifn/edgetunnel > Related, does waiting for I/O count as "cpu time"? No. > but most of that will be waiting for packets to flow back and forth. If you don't await on the contents but simply pipe the streams in and out, you should be well within CPU-related limits.
- eurleif 3y ago>What's the source IP for these sockets? Is it consistent across requests? Just did some brief testing. For me, the source IP wasn't consistent, but it was from an IP range belonging to Cloudflare. Notably, however, it wasn't from one of the IP ranges listed at https://www.cloudflare.com/ips/ https://www.cloudflare.com/ips/ unlike requests made from a Worker via `fetch()`. So, if you initiate two requests from the same worker -- one with `connect()`, and the other with `fetch()` -- then the first request uses a source IP belonging to Cloudflare but not from a range listed on their IP range page, while the second uses a source IP from a range listed on their IP range page. I suspect the reason for the different behavior is to do with the `Cf-Worker` header that `fetch()` adds, which enables applications to differentiate requests made by a Worker from requests made by Cloudflare itself. Raw TCP sockets can't add headers, so they need to differentiate themselves another way.
- kentonv 3y agoYes, that's correct, and yes, that's the reason. :)
- cojo 3y agoAs someone who built quite a bit of tech / product on Workers / Pages over the last year and a half or so, this (and some other announcements from this week) really excites me and I wish our timing had been better. Not being able to meaningfully use any external services that didn’t support an HTTP / fetch API was one of the biggest consistent pain points. Arguably it was the one with the biggest negative architectural ramifications. Given how long (understandably) it has taken to move D1 forward in the ways that matter most (e.g. transaction support), this is a huge step towards production viability for a more diverse range of products. When I left my company in April I had Cloudflare as a “glad I tried it, but not ready for production use / that was a mistake” - this week has it back on my list for evaluation on whatever I do next. Congrats to the Cloudflare team! I admire your intuition for what customers need and your willingness to compete with yourself on stuff like this (actively support other DB providers while building D1 - respect).
- lucasyvas 3y agoSane assessment - The transaction API for D1 will be so important as well. I've not been that excited for their approaches so far, but I also know of no other good alternative. Something I quite like doing is a thread-local (or async-local) context transaction, and that seems quite hard to do if not impossible with both batching and stored procedures from what I've seen. What I really wish for is to drop in any old query builder or ORM and use it identically to how I would with SQLite. I'm not sure if that's feasible, however.
- kentonv 3y agoSo, a challenge here is that SQLite is designed for single-writer scenarios. One writer performing a transaction necessarily has to block any other writer from proceeding in the meantime. (There are some experimental approaches in the works to solve this, like "BEGIN CONCURRENT", but it's still limited compared to a typical multi-client database.) This is all fine when the application is using SQLite as a local library since any particular transaction can finish up pretty quick and unlock the database for the next writer. But D1 allows queries to be submitted to the database from Workers located around the world. Any sort of multi-step transaction driven from the client is necessarily going to lock the database for at least one network round trip, maybe more if you are doing many rounds of queries. Since D1 clients could be located anywhere in the world, you could be looking at the database being write-locked for 10s or 100s of milliseconds. And if the client Worker disappears for some reason (machine failure, network connectivity, etc.), then presumably the database has to wait some number of seconds for a timeout, remaining locked in the meantime. Yikes! So, the initial D1 API doesn't allow remote transactions, only query batches. But we know that's not good enough. To actually enable transactions, we need to make sure the code is running next to the database, so that write locks aren't held for long. That's complicated but we're attacking it on a few different fronts. The new D1 storage engine announced a couple weeks ago (which has been my main project lately) is actually a new storage engine for Durable Objects itself. When it's ready, this will mean that every Durable Object has a SQLite database attached, backed by actual local files. In a DO, since the database is local, there's no problem at all with transactions and they'll be allowed immediately when this feature is launched. But DO is a lower-level primitive that requires some extra distributed systems thinking on the part of the developer. For people who don't want to think about it, D1 needs to offer something that "just works". The good news is that the Workers architecture makes it pretty easy for us to automatically move code around, so in principle we should be able to make a Worker run close to its D1 database if it needs to perform transactions against it. (We launched a similar feature recently, Smart Placement, which will auto-detect when a Worker makes lots of round trips to a single back-end, and moves the Worker to run close to it.) Sorry it's not all there yet, but we're working on it...
- jon4s 3y agoToo bad port 25 is not allowed. I assume the same restriction is placed on "Email Workers" that use the connect API?
- Manouchehri 3y agoIs there an large need for this? MailChannels works if you want free outgoing mail. (We use AWS SES for our Workers since the lack of webhook events with MailChannels for delivery events is kinda a problem.)
- jon4s 3y agoWhen building an email service, a few subrequests per mail send from a Worker acting as an SMTP server will be cheaper than the extra $ per millon mails for the API at MailGun/MailChannels/SES.
- Manouchehri 3y agoI don’t understand how $0 per outgoing email with MailChannels will cost more than $0 for a million emails. For incoming emails, Cloudflare Email Workers are $0 per email and SendGrid is also $0 per email. We only pay for the cost of the Worker with this setup.
- ttul 3y agoMailChannels CEO here. Would you pay something to get access to webhooks for delivery notifications and click-tracking? We have it; it's just not exposed.
- Manouchehri 3y ago1. Would pay for webhook delivery notifications as long as it isn’t more expensive than AWS SES. 2. Would not pay for click tracking. Might use it if it’s free. 3. We probably won’t use MailChannels again yet since we want to use AMP emails and ticket #221628 was handled pretty poorly. (We made our own MailChannels-like API for AWS SES after the frustrating experience.)