Building an API across multiple workers

Looking at building a large API with Cloudflare workers with about 60 endpoints. It would be crazy to build all in one worker, right? I considered using Hono and npmn workspaces to share code between workers where needed. Has anyone done this before? Looking at most guides everyone has a worker with four endpoints. Last thought has does it work mapping a domain say api.example.com to multiple workers?
7 Replies
kian
kian14mo ago
It's all personal preference, really. You can split it up into multiple files, multiple Workers, whatever works best for you. Until you're hitting the boundaries of Worker bundle limits (at which point you'll start to hit cold start penalties, or simply hit the limit and you can't publish anymore), there's no right or wrong answer. You can have src/users/index.ts that contains the routes for /users/ - or you can have a users Worker that is only bound to the route for example.com/users/*
AlexanderKaran
AlexanderKaranOP14mo ago
I was thinking of splitting each route into its own worker i.e /users -> all sub routes and actions in one worker /accounts -> all sub routes and actions in another worker I just can't see an API this size fitting all into one worker especialy due to the logic that needs to happen in endpoints (carbon and emission tracking) Is there a best practice on sharing code between workers or is all in one repo using pnpm good?
kian
kian14mo ago
Workers can be pretty big as far as code goes, due to minifying and the limits being on the gzip’d size, but if several Workers is better for you as far as workflow/management then there’s nothing wrong with it. You can easily call Workers with very low overhead using Service Bindings, which is an alternative option to sharing code - but requesting a Worker via Service Bindings will bill you a request like invoking it normally. As for the pnpm side of things, I’ve never had to manage a project that needed splitting so I’ll leave that for someone more experienced with it to comment on.
AlexanderKaran
AlexanderKaranOP14mo ago
What is a workers limit and thank you so much for the advice so far
kian
kian14mo ago
Limits · Cloudflare Workers docs
You can request adjustments to limits that conflict with your project goals by contacting Cloudflare. To request an increase to a limit, complete the …
kian
kian14mo ago
Whenever you do development or deployments with Wrangler it’ll tell you the size of your Worker
AlexanderKaran
AlexanderKaranOP14mo ago
Cool Yeah going to have to split this up lol Thanks Kian
Want results from more Discord servers?
Add your server