How to use Nodejs clustering with Sveltekit

91 views Asked by At

How is it possible to use the Node Cluster module with Sveltekit? In a classic node app, clustering is achieved by starting forks and serving the requests from the forks eg

const cluster = require('node:cluster');
const http = require('node:http');

if(cluster.isMaster){
  cluster.fork();
  cluster.fork();
} else {
  const server = http:createServer((req, res)=>{
    // serve request
  })
}

However, Sveltekit does not have a single nodejs entrypoint that can be assigned to a cluster fork. Sveltekit simply sends requests to each route as they come in. The closest thing to a single entry point is the hooks.server.js. Would this be the right place to create the clusters eg

// hooks.server.js
const cluster = require('node:cluster');

if(cluster.isMaster){
  cluster.fork();
  cluster.fork();
} else {

  export const handle = async({ event, resolve }) =>{
    // server handle
  }

}
1

There are 1 answers

0
necauqua On

However, Sveltekit does not have a single nodejs entrypoint

It does, in fact: https://kit.svelte.dev/docs/adapter-node#custom-server

So when you build your sveltekit app with adapter-node you can run this entrypoint from a custom clustered nodejs server, just like you wanted.