Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

PM2 Clusters

Blue Mouse0223ece78c0f
diff --git a/backend/apps/production/src/app.module.ts b/backend/apps/production/src/app.module.ts
index 3ff80099e..408677fc6 100644
--- a/backend/apps/production/src/app.module.ts
+++ b/backend/apps/production/src/app.module.ts
@@ -27,6 +27,7 @@ import { OgImageModule } from './og-image/og-image.module'
import { IntegrationsModule } from './integrations/integrations.module'
import { HealthModule } from './health/health.module'
import { AppController } from './app.controller'
+import { isPrimaryClusterNode } from './common/utils'
const modules = [
ConfigModule.forRoot({
@@ -93,7 +94,9 @@ const modules = [
imports: [
...modules,
...(process.env.ENABLE_INTEGRATIONS === 'true' ? [IntegrationsModule] : []),
- ...(process.env.IS_MASTER_NODE === 'true' ? [TaskManagerModule] : []),
+ ...(process.env.IS_MASTER_NODE === 'true' && isPrimaryClusterNode()
+ ? [TaskManagerModule]
+ : []),
],
controllers: [AppController],
})
diff --git a/backend/apps/production/src/common/utils.ts b/backend/apps/production/src/common/utils.ts
index 698e12cc9..ed802b476 100644
--- a/backend/apps/production/src/common/utils.ts
+++ b/backend/apps/production/src/common/utils.ts
@@ -151,6 +151,21 @@ export const millisecondsToSeconds = (milliseconds: number) =>
export const generateRandomString = (length: number): string =>
randomstring.generate(length)
+/**
+ * This is used to determine if the current node is the primary node.
+ *
+ * NODE_APP_INSTANCE is set to 0 (or undefined if not running on PM2) on primary node, and any other number on secondary nodes.
+ *
+ * @see https://pm2.keymetrics.io/docs/usage/environment/#specific-environment-variables
+ */
+export const isPrimaryClusterNode = () => {
+ if (!process.env.NODE_APP_INSTANCE) {
+ return true
+ }
+
+ return process.env.NODE_APP_INSTANCE === '0'
+}
+
const dummyLookup = () => ({
country: {
names: {
diff --git a/backend/ecosystem.config.js b/backend/ecosystem.config.js
new file mode 100644
index 000000000..3f51a8896
--- /dev/null
+++ b/backend/ecosystem.config.js
@@ -0,0 +1,10 @@
+module.exports = {
+ apps: [
+ {
+ name: 'Swetrix API',
+ script: './dist/main.js',
+ exec_mode: 'cluster',
+ instances: 2, // 'max',
+ },
+ ],
+}