---
title: "Building an Uptime Kuma Cluster with Vibe Coding: From Standalone to High-Availability Monitoring Platform"
description: "Using the Vibe Coding approach, a step-by-step guide to upgrading Uptime Kuma from standalone to a cluster-capable high-availability monitoring system — covering Docker Compose, load balancing, shared databases, and full Failover."
canonical_url: "https://blog.markkulab.net/en/post/implement-uptime-kuma-cluster-vibe-coding"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/en/author/mark-ku"
site: "Mark Ku's Tech Notes"
date_published: "2025-08-18T18:30:00.000Z"
date_modified: "2026-06-21T16:51:19.000Z"
category: "DevOps"
tags: ["uptime kuma", "cluster", "vibe coding", "docker", "mariadb", "load balancer", "monitoring", "high availability", "openresty"]
language: "en"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "when reusing or quoting, credit the author and link back to the original"
---

# Building an Uptime Kuma Cluster with Vibe Coding: From Standalone to High-Availability Monitoring Platform

> **TL;DR** — Upgrade Uptime Kuma to a cluster using Vibe Coding, Docker Compose, and MariaDB for high availability.

## Preface

Uptime Kuma is an open-source monitoring tool — already great out of the box. But if you need to monitor more than 1,000 APIs on a single instance, things start getting sluggish. In this article I'll use **Vibe Coding** to walk through upgrading Uptime Kuma into a version that supports **sharding** and **clustering**, plus add APIs for easier automation.

## Why bother with a Cluster?

First, the requirements.
Uptime Kuma is open-source monitoring software. [I previously shared how to switch its backend to MariaDB](https://blog.markkulab.net/uptime-kuma-mariadb-restful-api/). We replaced the default SQLite with MariaDB, deployed independently as `kuma-mariadb`, to support higher concurrent reads/writes.

However, once monitoring scales past 1,000 APIs, performance noticeably drops — real testing confirmed sluggishness as the count grows. Uptime Kuma is a Node.js app, and Node.js's single-threaded architecture inherently has a performance ceiling under heavy concurrency. That led me to also research [practical solutions for Node.js single-thread performance limits](https://blog.markkulab.net/post/nodejs-worker-threads-bun-performance).

Plus, our department's systems need to monitor nearly 4,000 APIs — a single Uptime Kuma instance just won't cut it.

For services with SLA-based billing, monitoring downtime can mean direct contractual penalties — the monitoring platform itself must be highly available.

Also, open-source Uptime Kuma doesn't support a RESTful API, which is very inconvenient for "API automatically goes live and becomes monitored" workflows. To avoid extra container deployment cost, we extended a RESTful API directly into Uptime Kuma.

Based on these needs and limitations, **Cluster architecture** is the natural answer, ensuring:

* **Fault tolerance / failover**: nodes can fail without service interruption
* **Load distribution**: multiple instances share the load — more stable performance
* **High availability**: avoid single points of failure, transparent and reliable data
* **Automation**: API-driven monitoring creation — easier for DevOps

## Break down requirements, organize ideas, plan and implement with Vibe Coding

In the spirit of Vibe Coding: break the requirements into small pieces, then build piece by piece. For larger and more complex projects, ask AI to draft a plan or guideline first, iteratively refine the AI-written plan, and finally have AI execute it.


### 1. Sharding support

Different monitors need to be distributed to different nodes:

* Add / modify / delete nodes
* Clearly indicate which node each monitor runs on
* On container start, auto-register the node into the database

### 2. Health Check

Use **Nginx / OpenResty + Lua (`health_check.lua`)** for node health checks:

#### Nginx Job mechanism

OpenResty provides a powerful scheduled-task mechanism — easily implement periodic health checks via **`ngx.timer.at()`**:

* **`init_worker_by_lua_block`**: runs when each worker process starts; initializes the health-check timer
* **`ngx.timer.at(delay, callback)`**: creates a one-shot timer that runs the callback after the specified delay
* **Recursive timers**: in the `health_check_worker` callback, after running the health check, call `ngx.timer.at()` again — forming a periodic loop
* **Avoid duplicate execution**: use `ngx.shared.DICT` or marker variables to ensure each worker only starts one health-check task

This design keeps health checks running entirely inside Nginx workers — no extra external process or cron job needed. Efficient and reliable.

#### Health-check flow

* OpenResty's worker periodically calls `health_check_worker`, running `run_health_check` at fixed intervals
* For each node, call `/api/v1/health` for an HTTP health check
* On consecutive failures → mark the node's status in the DB `node` table as `offline`
* On consecutive successes → update `node.status` back to `online` and trigger the "monitor restoration" flow

### 3. Failover

When a node dies, monitoring tasks must auto-migrate. This is handled by `health_check.lua` plus the database:

* Add a dedicated `node` table and node-related fields in the DB to record each node's `status`, `last_seen`
* The `monitor` table records each monitor's current `node_id` (and `assigned_node` when needed)
* When a node fails health check several times consecutively:
  * health_check marks the node as `offline`
  * Calls `redistribute_monitors_from_node(node_id)` to evenly distribute the monitors that node was responsible for to other `online` nodes
* When the node recovers (consecutive successful checks):
  * health_check marks the node as `online`
  * Calls `revert_monitors_to_node(node_id)` to move auto-migrated monitors back to the original node, preventing long-term imbalance

### 4. Node Recovery

Recovered nodes need to come back automatically:

* Auto-register on restart, status set to `online`
* The system moves migrated monitors back
* Ensure no duplicate execution, prevent data conflicts
* Also provide **manual recovery** — let admins decide whether to migrate back

### 5. RESTful API extension

Automation extension (RESTful API Extension): since native Uptime Kuma lacks an external API, to achieve "service goes live → automatically monitored" automation, we extended a RESTful API that automatically sets up monitoring when APIs are onboarded.

Uptime Kuma actually has plenty of built-in logic — it just doesn't expose APIs (everything goes through WebSocket). Knowing that, we can ask AI to expose the Service as APIs, making automation much easier.

### 6. OpenResty unified entry and load balancing

To present a single external entry point while internally distributing traffic among multiple Kuma nodes, we use OpenResty as the unified proxy and routing layer. This entry dynamically selects target nodes based on health and load, while handling real-time communication, APIs, and static content proxying. When a node fails, it auto-bypasses; when recovered, it re-flows — ensuring scalability and fault tolerance.

### 7. Manual node switching

On top of automatic load balancing and Failover, provide a "manual node switching" capability: admins can switch single or multiple monitoring tasks to a specific node, drain a node before maintenance, or temporarily lock/pin total traffic to a specific node (including pinning via Cookie). These manual operations cooperate with existing health-check and auto-migration mechanisms — they don't conflict.



## System architecture

```
System Architecture

                              ┌────────────────────────────┐
                              │   OpenResty (Nginx + Lua)  │
                              │  ─ Load balancer (monitor_router) │
                              │  ─ Health check (health_check)    │
                              └─────────┬──────────────────┘
                                        │
                     ┌──────────────────┼────────────────────┐
                     │                  │                    │
          ┌───────────▼─────────┐ ┌─────▼────────────┐ ┌─────▼────────────┐
          │   Uptime Kuma       │ │   Uptime Kuma    │ │   Uptime Kuma    │
          │   Node 1            │ │   Node 2         │ │   Node 3         │
          │   (Port 3001)       │ │   (Port 3001)    │ │   (Port 3001)    │
          │   (Host: 9091)      │ │   (Host: 9092)   │ │   (Host: 9093)   │
          └─────────┬───────────┘ └─────┬────────────┘ └──────┬───────────┘
                    │                   │                     │
                    └───────────────────┼─────────────────────┘
                                        │
                              ┌─────────▼─────────┐
                              │     MariaDB       │
                              │   (Port 3306)     │
                              │   (Host: 9090)    │
                              └───────────────────┘
```

Key components:

- **OpenResty / Nginx**: only defines a virtual `upstream uptime_kuma_cluster` in `nginx.conf`; the actual node selection is delegated to Lua.
- **`monitor_router.lua`**: invoked in `balancer_by_lua_block`, providing `pick_node_for_request()` — dynamically picks the least-busy node based on each node's current "running monitor count," and routes via `ngx.balancer.set_current_peer()` to the corresponding `uptime-kuma-nodeX` container.
- **`health_check.lua`**: periodically scans node health, updates the DB `node` table, and triggers automatic monitoring task migration and restoration on node failure/recovery.

## Flow diagrams

### 1. Load balancing and routing flow (monitor_router.lua)

```
Request flow

Client Request
      │
      ▼
Nginx / OpenResty
  (location /, /api/, /socket.io/ → proxy_pass to uptime_kuma_cluster)
      │
      ▼
balancer_by_lua_block
  calls monitor_router.pick_node_for_request()
      │
      ▼
Query DB:
  SELECT n.node_id, COUNT(m.id) AS monitor_count
  FROM node n
  LEFT JOIN monitor m ON m.node_id = n.node_id AND m.active = 1
  WHERE n.status = 'online'
  GROUP BY n.node_id
  ORDER BY monitor_count ASC, node_id ASC
      │
      ▼
Pick the online node with the fewest monitors (e.g., node2)
      │
      ▼
Compose upstream: uptime-kuma-node2:3001
      │
      ▼
ngx.balancer.set_current_peer("uptime-kuma-node2", 3001)
      │
      ▼
Request actually forwarded to the corresponding Uptime Kuma node
```

### 2. Health check and Failover / Recovery flow (health_check.lua)

```
Health check and auto-migration flow

Health check worker periodically runs run_health_check()
      │
      ▼
Query DB to get all nodes (node table)
      │
      ▼
For each node, call /api/v1/health
      │
      ├── Healthy: update node.status = 'online', reset failure count;
      │           on consecutive successes trigger revert_monitors_to_node(node_id)
      │
      └── Failed: accumulate failure count; once threshold is reached,
                 set node.status = 'offline' and trigger
                 redistribute_monitors_from_node(node_id),
                 evenly distributing monitors to other online nodes
      │
      ▼
Health status and stats written to DB + ngx.shared.health_checker
      │
      ▼
Expose overall status externally via /health, /api/health-status, /lb/health, /lb/capacity APIs
```

## Results

![Uptime Kuma dashboard showing service up and down status](https://blog.markkulab.net/content/markku/posts/implement-uptime-kuma-cluster-vibe-coding/images/螢幕截圖1.jpg)
![Uptime Kuma nodes settings displaying three online cluster nodes](https://blog.markkulab.net/content/markku/posts/implement-uptime-kuma-cluster-vibe-coding/images/螢幕截圖2.jpg)
![Uptime Kuma API documentation in Swagger UI showing health endpoints](https://blog.markkulab.net/content/markku/posts/implement-uptime-kuma-cluster-vibe-coding/images/螢幕截圖3.jpg)

After discussing with my supervisor, since we take from the community we give back to the community — the related code is open-sourced:

[Uptime Kuma Cluster GitHub repo](https://github.com/markku636/uptime-kuma-cluster)

## Reflections
The AI era may have multiplied productivity by 5–10×, freeing us from typing every line by hand. But during later maintenance, we discover insufficient familiarity with the code. This drives home a deep lesson: no matter how tools evolve, someone ultimately needs to truly understand and maintain the code. Technical depth and comprehension remain irreplaceable.

## Further reading
* [Practical solutions for Node.js single-thread performance bottlenecks](https://blog.markkulab.net/post/nodejs-worker-threads-bun-performance)
* [Uptime Kuma official docs](https://github.com/louislam/uptime-kuma)
* [Docker Compose official docs](https://docs.docker.com/compose/)
* [OpenResty official docs](https://openresty.org/)
* [MariaDB official docs](https://mariadb.org/)
* [Lua programming language](https://www.lua.org/)

---

## About this article and its author

Originally published on [Mark Ku's Tech Notes](https://blog.markkulab.net/en/post/implement-uptime-kuma-cluster-vibe-coding)

License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — when reusing or quoting, credit the author and link back to the original

### About the author

**[Mark Ku](https://blog.markkulab.net/en/author/mark-ku)** — Software engineer

- 10+ years as a software engineer
- Built North-American e-commerce and AI SaaS subscription billing

### Free tools built by the author

All of these are free to use:

- [Free PDF Sign Tool](https://blog.markkulab.net/en/tools/pdf-sign): Online PDF sign tool — draw, type, or upload a signature, then drag, resize, and download. Everything runs in your browser; nothing is uploaded.
- [VS Code Refactory](https://blog.markkulab.net/en/tools/refactory): Refactory is a VS Code refactoring extension: 34 actions plus a 37-rule code-smell inspection layer with a Code Health dashboard, across 18 languages, backed by 534 tests. It learns your repo's conventions: where interfaces live, where DI is registered, whether 'use client' belongs. It ranks files by git churn × complexity so you know what to fix first, and hands any smell to the Claude Code already on your machine. Free to use, and your source never leaves your computer.
- [DB-Kit Database Manager](https://blog.markkulab.net/en/tools/db-kit): DB-Kit is a lightweight, cross-platform database manager built with Tauri + Rust + React. Manage MySQL, MariaDB, PostgreSQL, SQL Server, Oracle, SQLite, MongoDB, Redis, Kafka, Elasticsearch and RabbitMQ from one consistent interface: passwords encrypted in the OS keychain, SSH tunnels, full CRUD, a visual query builder, stacked multi-statement result sets, cross-connection data transfer, schema & data compare with sync SQL and schema snapshots, Excel / CSV import & export, visualized execution plans, ER diagrams, scheduled backups, SQL stress testing with p50–p99 latency percentiles, a 15-rule SQL review engine, Review & Run (AI review plus per-statement backups and an auto-generated rollback script), Kafka message browsing with monitoring & alerts, an SSH terminal with SFTP / FTP, Docker / Kubernetes, remote desktop (RDP / VNC / RustDesk), file / folder compare, stored procedure integration tests, six UI languages, a built-in AI assistant (a local CLI or any Anthropic / OpenAI-compatible API; natural-language SQL, AI review and tuning advice) and the dbk CLI. Free and open source (MIT), with installers for Windows, macOS and Linux.
- [VS Code Super Mermaid](https://blog.markkulab.net/en/tools/super-mermaid): Super Mermaid is a VS Code extension for beautiful Mermaid diagrams out of the box: auto-colored live preview, mouse pan & zoom, high-res PNG / SVG export, 21 templates and multiple themes. Free and open source (MIT).
- [React Super Mermaid](https://blog.markkulab.net/en/tools/react-super-mermaid): react-super-mermaid is an open-source React component library: render beautiful Mermaid diagrams with a single <MermaidViewer>, with built-in colorful / sketch themes, pan & zoom, in-diagram search, and high-res SVG / PNG export. Lightweight, SSR-safe, fully typed. Free and open source (MIT).
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/en/tools/jira-super-mermaid): An Atlassian Forge app: write Mermaid syntax directly inside a Jira issue or a Confluence page and get flowcharts, sequence diagrams, state machines and Gantt charts. 11 diagram types, SVG / PNG export, light and dark themes, full CJK support. Runs on Atlassian: your diagrams live in your own site and the app calls no third-party service. Free, coming soon to the Atlassian Marketplace.
- [Mermaid Live Preview](https://blog.markkulab.net/en/tools/mermaid-preview): Write Mermaid in your browser, see it render instantly, and share the whole diagram as a single link. No sign-up, nothing uploaded to a server, and mermaid.live share links work as-is.
- [React Intl Phone Number](https://blog.markkulab.net/en/tools/react-intl-phone-number): react-intl-phone-number is an open-source React component: framework-agnostic and antd-free, with E.164 in/out, a searchable flag / country-code dropdown, configurable validation levels (strict / mobile-strict / loose), themeable CSS, and i18n — phone logic powered by google-libphonenumber. Lightweight and fully typed. Free and open source (MIT).
- [Uptime Kuma Cluster](https://blog.markkulab.net/en/tools/uptime-kuma-cluster): Turn single-node Uptime Kuma into a highly available cluster: OpenResty + Lua smart load balancing, shared MariaDB state, health checks and automatic failover, plus cluster-management REST APIs. One Docker Compose command to start. Free and open source (MIT).
- [AI Podcast Cut](https://blog.markkulab.net/en/tools/ai-podcast-cut): Drop in a recording and it removes fillers and stutters, levels loudness segment by segment, and sends a second agent to review every cut. Cut points snap to word boundaries and zero crossings, every splice gets a fade, and sentence-end breaths are preserved. Desktop app for Windows, macOS and Linux. MIT licensed; the Windows installer bundles ffmpeg.
- [AI Video Cut](https://blog.markkulab.net/en/tools/ai-video-cut): Pick something in your video: type it (face, license plate, phone screen, logo), click points or drag a box, or let Claude Code / Codex pick it. AI Video Cut tracks it frame by frame, then mosaics or blurs it, recolors it, pins stickers and text to it, swaps a screen or poster for your own image or video, or removes it using background that other frames actually captured. Plus sequence editing, local captions and an AI assistant. Free, open-source (MIT) Windows desktop app (macOS / Linux experimental) that runs locally, nothing uploaded.
- [open-pos restaurant POS](https://blog.markkulab.net/en/tools/open-pos): One computer and one receipt printer is enough to open the shop. Your data lives on your own disk, no subscription, no lock-in, MIT licensed. Money is integer New Taiwan dollars with tax split by the statutory formula, so sales + tax always equals the total. Printing goes straight over ESC/POS on TCP 9100, with no vendor driver. Tauri + Rust + SQLite desktop app, v1.0 in development.
- [.NET e-commerce API template](https://blog.markkulab.net/en/tools/dotnet-ecommerce-api): An e-commerce backend API template built on .NET 10: Controller → Service → Repository layering, Autofac convention-based registration, SqlSugar for MySQL / MariaDB and SQL Server, Redis cache and message queue, Hangfire jobs, JWT auth, and an extensible payment provider module (ECPay, Newebpay). Apache 2.0.

### Daily podcasts

- [Mark's Tech Insights — Daily AI News](https://blog.markkulab.net/en/category/tech-news): Daily curated AI and tech trends. Catch the latest developments via audio summaries — covering AI applications, software architecture, DevOps, and engineering practice. — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/en/category/ai-stock-chat): Every trading day, an AI-analyzed take on the Taiwan stock market, delivered as a two-host conversation covering the session and the next-day outlook. — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml
- [開源好物週報](https://blog.markkulab.net/en/category/open-source-weekly): A weekly two-host pick of free open-source tools surfaced from real Hacker News, GitHub, and Reddit buzz — what pain they solve and the fastest way to get started. — RSS: https://blog.markkulab.net/open-source-weekly/feed.xml
- [AI 運動週報](https://blog.markkulab.net/en/category/sports-weekly): Two hosts talk NBA, MLB and world sport three times a week — scores, records and the stories behind them, from a Taiwanese fan perspective. — RSS: https://blog.markkulab.net/sports-weekly/feed.xml
- [AI 國際新聞快報](https://blog.markkulab.net/en/category/world-news): A daily two-host briefing that makes sense of the past 24 hours in world news — geopolitics, the global economy, conflict and security, disasters and climate — from a Taiwanese perspective, neutral and fully sourced. — RSS: https://blog.markkulab.net/world-news/feed.xml
- [地端 AI 實驗室](https://blog.markkulab.net/en/category/local-ai-lab): Twice a week, a two-host look at open-weight models and LoRAs you can actually run on your own machine: what they are for, whether your GPU can handle them, and how they compare — sourced from official model cards. — RSS: https://blog.markkulab.net/local-ai-lab/feed.xml

### Deals

- [Saily eSIM](https://blog.markkulab.net/en/saily): Travel eSIM by the NordVPN team，Promo code：KUKU
- [NordVPN](https://blog.markkulab.net/en/nordvpn): The world's leading VPN, independently audited
- [PremLogin](https://blog.markkulab.net/en/premlogin): Subscription sharing for streaming and AI seats，Promo code：markku666

### Newsletter

[Subscribe to the newsletter](https://blog.markkulab.net/en/subscribe) — Be the first to know about new posts. No spam, unsubscribe anytime.
