Platform Automation & Cloud Infrastructure
NexaLibre
A multi-tenant SaaS orchestrator built for Spartan IT to automate VPS container lifecycles, dynamic reverse proxies, and zero-collision port allocation.
The Operational Friction: The 45-Minute CLI Bottleneck
At Spartan IT, delivering managed hosting for client workloads—ranging from WordPress instances and BookStack knowledge bases to custom databases and internal tools—was initially entirely manual.
For every client onboarding, a systems engineer had to:
- SSH into a raw Ubuntu VPS host and manually partition isolated directory structures (
/opt/...or/home/...). - Generate Jinja-style Docker Compose configurations and inject environment variables by hand.
- Track assigned host ports across a shared team spreadsheet to prevent overlapping port bindings.
- Manually configure Nginx reverse proxy upstream blocks, reload Nginx, and trigger Certbot for Let's Encrypt SSL certificates.
- Provision isolated MySQL databases and user privileges.
This workflow averaged 45 minutes of command-line operations per application. Worse, it created dangerous operational vulnerabilities:
- Blast Radius Risks: A single syntax error or missing semicolon in one client's Nginx upstream block could fail the entire Nginx reload, taking down existing client apps on that host.
- Port Collisions: Simultaneous deployments by different engineers frequently picked overlapping port numbers, crashing Docker daemon startups.
- Certificate Limits: Manual Certbot requests occasionally bumped against Let's Encrypt rate limits during batch client rollouts.
To eliminate this operational friction, I led the architecture and development of NexaLibre—a decoupled, multi-tenant cloud orchestration platform that transforms manual sysadmin tasks into an automated, sub-2-minute web workflow.
The Decoupled 4-Tier Architecture
To isolate security boundaries and ensure horizontal scalability, I designed NexaLibre around a four-tier architecture separating the central control plane from edge routing and tenant VPS compute:
- Central Control Plane (Django 5 & Django REST Framework): Runs on a secured primary node. Manages user authentication (JWT via secure HTTP-only cookies), Stripe subscription billing, product catalog templates, and the global Finite State Machine (FSM) in MySQL.
- Asynchronous Execution Pipeline (Celery & Redis): Prevents HTTP request timeouts by decomposing provisioning into an idempotent task chain (
check_domain→cloudflare_dns_setup→vps_deploy_container→nginx_host_setup). - Edge Ingress & Automated Routing (Cloudflare DNS & Nginx Proxy Manager): Orchestrates dynamic subdomain allocation through Cloudflare DNS-01 APIs and configures upstream reverse proxy hosts with automated SSL termination and WebSocket upgrades via the NPM REST API.
- Remote Host Daemon (FastAPI / Flask Agent): A lightweight agent deployed on each tenant VPS host behind local firewalls. Authenticated via rotating bearer tokens, it executes container lifecycle commands, writes templated compose files, and performs raw kernel socket verification.
Challenge 1: Zero-Collision Port Allocation (Atomic Transactions + OS Socket Probing)
On multi-tenant VPS nodes running multiple client containers, choosing host ports without collisions is a classic distributed concurrency challenge. Two concurrent Celery workers might calculate the same port as available, or an unmanaged host daemon might already bind to that port.
I engineered a two-gate allocation mechanism combining atomic database locks with physical Linux kernel socket probing:
- Gate 1 (Atomic Database Reservation): The allocator queries currently allocated ports from MySQL. It iterates upward from a seed port and immediately attempts to insert a
PortReservationrecord wrapped intransaction.atomic(). The database enforces aunique_together = (('server', 'port', 'active'),)constraint. If another worker attempts to claim the same port in parallel, the unique index trips anIntegrityError, causing the worker to increment and attempt the next candidate port cleanly. - Gate 2 (Remote Kernel Socket Verification): Once reserved in the database, the coordinator makes an authenticated call to the remote VPS daemon's
/check_portendpoint. The agent creates a raw TCP socket and executessock.connect_ex(("127.0.0.1", port)). If the socket connection succeeds (connect_ex == 0), an untracked process is actively listening on that port. The allocator releases the DB reservation and moves to the next port.
# nexalibre_backend/PaymentSetup/vps_api.py
def check_or_find_port_availability(port, max_attempts=100, deployment_id_to_exclude=None,
server: Optional[VPSServer] = None,
deployment: Optional[Deployment] = None):
"""
Scans upward from seed port. Performs dual-gate validation:
1. Database-level atomic reservation with unique constraint.
2. Host-level physical socket connection check via remote agent.
"""
attempt = 0
used_ports = get_used_forward_ports(exclude_deployment_id=deployment_id_to_exclude, server=server)
while attempt < max_attempts:
if port in used_ports:
port += 1
attempt += 1
continue
# Gate 1: Atomic DB Reservation with unique constraint
reservation = None
if server is not None:
try:
with transaction.atomic():
reservation = PortReservation.objects.create(
server=server,
port=port,
deployment=deployment,
active=True,
)
except IntegrityError:
# Port already reserved concurrently by another worker
port += 1
attempt += 1
continue
# Gate 2: Host OS Socket Probe
try:
response = request_api(
'POST', '/check_port', server=server, json={"port": port}, timeout=15
)
if response.status_code == 200 and response.json().get("available", False):
return port # Collision-free port confirmed
except Exception as e:
logger.warning(f"Host socket probe failed for port {port}: {e}")
# Port taken on host: release DB reservation and scan next
if reservation:
reservation.active = False
reservation.released_at = timezone.now()
reservation.save(update_fields=['active', 'released_at'])
port += 1
attempt += 1
raise RuntimeError(f"Exhausted {max_attempts} port allocation attempts on {server.name}")On the client VPS host, the private agent validates availability at the kernel socket layer:
# flask_api_from_vps/app.py
@app.route('/check_port', methods=['POST'])
def check_port():
"""Validates raw TCP socket availability on the VPS host."""
port = request.json.get('port')
if not port or not (1 <= port <= 65535):
return jsonify({"status": "error", "message": "Invalid port number"}), 400
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(1.0)
result = sock.connect_ex(("127.0.0.1", port))
# Port is available if connect_ex returns non-zero (connection refused/closed)
is_available = (result != 0)
return jsonify({"status": "success", "available": is_available}), 200Challenge 2: Dynamic Ingress Automation (Nginx Proxy Manager & Cloudflare API)
Automating edge routing required programmatic certificate issuance, wildcard DNS provisioning, and persistent WebSocket connectivity without service interruptions:
- Token Expiry Buffer: To prevent authentication drops during multi-step provisioning, I implemented an automated token manager that monitors JWT lifetimes and proactively requests a fresh bearer token 5 minutes prior to expiration.
- Certificate Discovery & Let's Encrypt: Before ordering a new certificate, the proxy layer inspects Nginx Proxy Manager's existing certificate cache (
find_existing_certificate(domain)). If a valid wildcard or domain certificate exists, it reuses the certificate ID; otherwise, it triggers a new Let's Encrypt ACME challenge. - WebSocket Reverse Proxy Pass-Through: WebSockets are mandatory for live log streaming. The proxy host creator automatically sets
allow_websocket_upgrade=True, injecting the requiredUpgrade $http_upgradeandConnection $connection_upgradeheaders into the generated Nginx upstream configuration. - Automated Cloudflare DNS Provisioning: Cloudflare API integration automatically verifies zone availability and configures CNAME and A records pointing client subdomains directly to the VPS ingress IP.
# nexalibre_backend/PaymentSetup/nginx_proxy_manager.py
def create_proxy_host(domain, forward_port, scheme="http", enable_ssl=False,
enable_block_exploits=True, enable_websocket=True,
letsencrypt_email=Username):
"""
Provisions a dynamic reverse proxy host in Nginx Proxy Manager with
automated SSL discovery and mandatory WebSocket upgrade flags.
"""
ensure_token_valid()
certificate_id = None
if enable_ssl:
certificate_id = find_existing_certificate(domain)
if not certificate_id:
certificate_id = "new"
url = f"{BASE_URL}/nginx/proxy-hosts"
payload = {
"domain_names": [domain],
"forward_scheme": scheme,
"forward_host": forward_host,
"forward_port": forward_port,
"access_list_id": 0,
"certificate_id": certificate_id,
"ssl_forced": enable_ssl,
"caching_enabled": False,
"block_exploits": enable_block_exploits,
"allow_websocket_upgrade": enable_websocket,
"advanced_config": "",
"meta": {
"letsencrypt_email": letsencrypt_email,
"letsencrypt_agree": True,
"dns_challenge": False,
},
}
response = requests.post(url, json=payload, headers=HEADERS, timeout=30)
return response.json()Challenge 3: Race-Condition Defense & Distributed State Safety
In a SaaS deployment pipeline, webhooks and billing events arrive concurrently. Stripe frequently fires customer.subscription.updated and invoice.payment_succeeded in parallel within 50ms of each other. Without concurrency protection, parallel workers would trigger double container builds or corrupt subscription tiers.
I built a three-layer state safety architecture:
- Deadlock-Free Lock Keys: To prevent distributed deadlocks during plan upgrades or downgrades that involve two subscription records, lock keys are sorted deterministically using minimum and maximum IDs:
- Pre-Flight Snapshotting & Rollback: Before any plan mutation or container migration begins, the system takes a complete state snapshot (
backup_deployment_state(subscription)). If container allocation fails on the destination node, the handler catches the exception, terminates the orphan container, and rolls back the database state to the pre-flight snapshot. - Database-Enforced State Machine: Every
Deploymentobject transitions through strict lifecycle states (DEPLOYING→RUNNING→STOPPED→DELETED/FAILED). State mutations must specify an audited reason (USER,SUBSCRIPTION_EXPIRED,ADMIN,FAILED_HEALTH_CHECK), preventing out-of-order webhook delivery from resurrecting stopped containers.
def get_plan_change_lock_key(new_sub_id, old_sub_id):
return f"plan_change:{min(new_sub_id, old_sub_id)}:{max(new_sub_id, old_sub_id)}"Idempotency & Webhook Deduplication: Every incoming Stripe webhook event is registered in a database WebhookEvent table within an atomic transaction. If an event ID already exists or Redis lock acquisition fails, the webhook immediately returns an HTTP 200 acknowledge without executing redundant background tasks.
Challenge 4: Zero-Downtime GitLab CI/CD & The Env Survival War Story
Production deployment safety was critical. During early deployments, an operational incident occurred: rsync -av --delete deployed updated repository files to the permanent production folder /home/nexalibre/nexalibre/. Because .env files are intentionally excluded from version control, the --delete flag wiped out the live production .env containing production database passwords and Stripe keys. Containers restarted with empty environment variables and crashed.
To eliminate this vulnerability permanently, I redesigned the production deployment stage in .gitlab-ci.yml with fail-safe verification and automated rollback protection:
- Pre-Deploy Live Tarball Snapshots: Before touching running code, the pipeline creates timestamped tarball archives of the live code (
code_live_backup.tar.gz), active.envfiles, user media directories, and Certbot SSL certificates. - Post-Rsync Environment Restoration: The pipeline validates that master environments exist in
/home/nexalibre/, executes thersyncsync, and immediately restores.envfiles after rsync before building containers. - Pre-Flight Nginx Configuration Testing: Before reloading traffic, the pipeline runs
docker compose exec nginx nginx -tinside the production container. If the configuration test fails, the deployment aborts with an error, preventing broken configs from interrupting production traffic. If valid, it triggersnginx -s reloadfor a seamless zero-downtime hot reload.
# .gitlab-ci.yml (Production Stage)
production:
stage: production
tags: [production]
only:
- Production
when: manual
script: |
set -euo pipefail
echo "=== PRODUCTION DEPLOY START ==="
cd "$CI_PROJECT_DIR"
# 1. Validate master env files exist
test -f /home/nexalibre/.env-prod-backend || (echo "Missing backend env!" && exit 1)
test -f /home/nexalibre/.env-prod-frontend || (echo "Missing frontend env!" && exit 1)
# 2. Backup running production code, live .envs, and SSL certs
export BACKUP_DIR="/home/nexalibre/backups/$(date +%F_%H-%M-%S)"
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/code_live_backup.tar.gz" -C /home/nexalibre/ nexalibre || echo "code backup warning"
cp /home/nexalibre/nexalibre/.env "$BACKUP_DIR/.env_live_backup" 2>/dev/null || true
tar -czf "$BACKUP_DIR/ssl_live_backup.tar.gz" -C /home/nexalibre/nexalibre certbot 2>/dev/null || true
# 3. Rsync new release to permanent prod directory
rsync -av --delete \
--exclude='.git' \
--exclude='node_modules' \
--exclude='backups' \
--exclude='certbot/' \
--exclude='nexalibre_backend/staticfiles/' \
--exclude='nexalibre_backend/media/' \
"$CI_PROJECT_DIR"/ /home/nexalibre/nexalibre/
cd /home/nexalibre/nexalibre/
# 4. CRITICAL FIX: Restore production envs AFTER rsync
cp /home/nexalibre/.env-prod-backend ./.env
cp /home/nexalibre/.env-prod-frontend ./front_end/.env
# 5. Build and launch updated containers
docker compose -f docker-compose.prod.yml up -d --build
# 6. Validate Nginx configuration syntax before hot reload
docker compose -f docker-compose.prod.yml exec nginx nginx -t \
|| (echo "Nginx test failed! Aborting reload." && exit 1)
# 7. Hot-reload Nginx without dropping active client connections
docker compose -f docker-compose.prod.yml exec nginx nginx -s reload
echo "=== PRODUCTION DEPLOY COMPLETED SUCCESSFULLY ==="Real-Time Observability: ASGI WebSockets & Daphne
To provide developers and clients with visibility into container provisioning, I engineered an event-driven telemetry stream using Django Channels and Daphne ASGI:
- Authentication via Cookie Inspection: WebSockets authenticate through a custom middleware (
ChannelsMiddleware) that parses the HTTP-only JWTaccess_tokencookie. Unauthenticated attempts are rejected immediately with custom close code4010. - Isolated User Channels: Each connected client joins a per-user channel group
f"user_{user.id}". Celery provisioning tasks broadcast real-time compilation milestones (DOCKER_BUILD_START,PORT_RESERVED,DNS_PROPAGATED,CONTAINER_READY) directly to the active user's session. - De-duplication Buffer: An in-memory notification cache inside
NotificationConsumertracks dispatched event IDs, guaranteeing that burst log updates do not flood the React frontend.
# nexalibre_backend/Notifications/consumers.py
class NotificationConsumer(AsyncWebsocketConsumer):
async def connect(self):
user = self.scope.get('user', None)
if user and user.is_authenticated:
self.group_name = f"user_{user.id}"
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.channel_layer.group_add("broadcast", self.channel_name)
await self.accept()
else:
await self.close(code=4010 if user is None else 4001)
async def disconnect(self, close_code):
if hasattr(self, 'group_name'):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
await self.channel_layer.group_discard("broadcast", self.channel_name)Quantified Outcomes & Engineering Impact
NexaLibre replaced manual, error-prone sysadmin practices with a deterministic cloud platform:
- 95% Reduction in Provisioning Time: Self-hosted application deployment plummeted from 45 minutes of manual CLI commands to under 2 minutes of automated web actions.
- Zero Port Collisions: Across hundreds of multi-tenant container deployments, the dual-gate allocator (
PortReservationatomic transactions + host kernel socket probes) maintained a 100% collision-free record. - Zero-Downtime Deployment Cycle: With pre-deploy live tarball snapshots and validated
nginx -treloads, Spartan IT achieved zero downtime during continuous production releases. - Tenant Isolation: Containerized workloads operate with isolated port assignments, independent volume mounts, and dynamic reverse proxy configurations, eliminating cross-tenant interference.
Key Achievements & Metrics
Architected a 4-tier multi-tenant orchestrator: Django 5 control plane, Daphne ASGI WebSockets, Celery task pipeline, and private VPS host agents.
Engineered a dual-gate port allocator combining MySQL atomic reservations with remote OS kernel socket verification (socket.connect_ex).
Automated edge ingress using Cloudflare DNS APIs and Nginx Proxy Manager REST APIs with token caching, Let's Encrypt SSL, and WebSocket upgrades.
Hardened production deployments using GitLab CI/CD with automated live tarball snapshots, post-rsync .env restoration, and zero-downtime Nginx hot reloads.
Spartan IT