Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/KevinhosUTP/Automatizacion-Lurwis/llms.txt

Use this file to discover all available pages before exploring further.

Production Deployment

Comprehensive guide to deploying Automatización Lurwis to production with enterprise-grade reliability and security.

Pre-Deployment Checklist

Infrastructure Requirements

Minimum Requirements:
  • CPU: 4 cores
  • RAM: 8GB
  • Storage: 100GB SSD
  • Network: 1Gbps
Recommended for High Traffic:
  • CPU: 8+ cores
  • RAM: 16GB+
  • Storage: 250GB SSD with daily backups
  • Network: 10Gbps
PostgreSQL:
  • Version: 12+
  • Connection Pooling: PgBouncer or built-in session pooler
  • Replication: Primary + read replica
  • Storage: 50GB minimum, with auto-scaling
MongoDB:
  • Version: 4.4+
  • Replica Set: 3 nodes minimum
  • Storage: 20GB for conversation history
Redis:
  • Version: 6+
  • Configuration: Standalone or cluster
  • Memory: 4GB minimum
  • Persistence: AOF enabled
  • WhatsApp Business API: Production access approved
  • Google Gemini API: Billing enabled, rate limits verified
  • Domain & SSL: Valid SSL certificate (Let’s Encrypt or commercial)
  • DNS: Properly configured with low TTL for failover

Security Hardening

Network Security

1

Enable HTTPS/TLS

Configure reverse proxy with SSL:Caddy (Recommended - Used in Workflows):
your-domain.com {
    reverse_proxy n8n:5678
    
    # Security headers
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Frame-Options "DENY"
        X-Content-Type-Options "nosniff"
        Referrer-Policy "strict-origin-when-cross-origin"
    }
    
    # Rate limiting
    rate_limit {
        zone webhook {
            key {remote_host}
            events 100
            window 1m
        }
    }
}
The Receptor workflow shows Caddy in use: via: 1.1 Caddy in the webhook headers.
2

Firewall Configuration

Allow only necessary ports:
# Allow HTTPS
ufw allow 443/tcp

# Allow SSH (restrict to your IP)
ufw allow from YOUR_IP to any port 22

# Deny all other incoming
ufw default deny incoming
ufw default allow outgoing
ufw enable
3

Database Security

PostgreSQL:
-- Enable Row Level Security
ALTER TABLE pedidos_picanteria ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY pedidos_isolation ON pedidos_picanteria
    USING (telefono = current_setting('app.current_user'));
Connection Security:
  • Use SSL/TLS for all database connections
  • Whitelist only n8n server IP
  • Use connection pooling to prevent exhaustion
4

API Security

WhatsApp Webhook Validation:The Receptor workflow validates Meta signatures:
x-hub-signature: sha1=...
x-hub-signature-256: sha256=...
Ensure signature verification is enabled in production.

Authentication & Authorization

# n8n Access Control
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=admin
N8N_BASIC_AUTH_PASSWORD=<strong-password>

# Additional Security
N8N_SECURE_COOKIE=true
N8N_JWT_AUTH_ACTIVE=true
Critical Security Requirements:
  • Change default credentials immediately
  • Use password manager for credential storage
  • Enable 2FA on all external services (Meta, Google Cloud)
  • Rotate API tokens every 90 days

High Availability Architecture

┌─────────────────────────────────────────┐
│         Load Balancer / Caddy            │
│        (SSL Termination)                 │
└────────────┬────────────────────────────┘

    ┌────────┴────────┐
    │                 │
┌───▼───┐        ┌───▼───┐
│ n8n   │        │ n8n   │  (Active-Passive)
│Primary│        │Standby│
└───┬───┘        └───────┘

    ├──────────┬─────────────┬──────────────┐
    │          │             │              │
┌───▼───┐  ┌──▼──┐     ┌────▼────┐   ┌────▼─────┐
│Postgres│  │Redis│     │ MongoDB │   │  Gemini  │
│(RDS)   │  │     │     │(Replica │   │   API    │
└────────┘  └─────┘     │  Set)   │   └──────────┘
                        └─────────┘

Container Orchestration

For single-server deployment:
version: '3.8'

services:
  n8n:
    image: n8nio/n8n:latest
    restart: unless-stopped
    ports:
      - "5678:5678"
    environment:
      - NODE_ENV=production
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=${N8N_USER}
      - N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD}
      - WEBHOOK_URL=${WEBHOOK_URL}
      - EXECUTIONS_PROCESS=main
      - N8N_METRICS=true
    volumes:
      - n8n_data:/home/node/.n8n
      - ./backups:/backups
    healthcheck:
      test: ["CMD", "wget", "--spider", "http://localhost:5678/healthz"]
      interval: 30s
      timeout: 10s
      retries: 3

  caddy:
    image: caddy:latest
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - n8n

volumes:
  n8n_data:
  caddy_data:
  caddy_config:

Scaling Strategy

Vertical Scaling

1

Identify bottlenecks

Monitor resource usage:
# CPU and memory
docker stats n8n-lurwis

# Workflow execution times
# Check n8n metrics endpoint
curl http://localhost:5678/metrics
2

Scale resources

For Docker:
deploy:
  resources:
    limits:
      cpus: '4'
      memory: 8G
    reservations:
      cpus: '2'
      memory: 4G

Horizontal Scaling

n8n currently has limitations with horizontal scaling due to webhook routing. Use queue mode for multi-instance deployments.
Queue Mode Configuration:
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=your-redis-host
QUEUE_BULL_REDIS_PORT=6379
QUEUE_BULL_REDIS_PASSWORD=your-password

Database Optimization

-- Create indexes for common queries
CREATE INDEX idx_pedidos_telefono ON pedidos_picanteria(telefono);
CREATE INDEX idx_pedidos_estado ON pedidos_picanteria(estado_pedido);
CREATE INDEX idx_pedidos_fecha ON pedidos_picanteria(created_at);

-- Vacuum regularly
VACUUM ANALYZE pedidos_picanteria;
Connection Pooling:
# PgBouncer configuration
[databases]
picanteria_db = host=postgres-host port=5432 dbname=picanteria_db

[pgbouncer]
pool_mode = session
max_client_conn = 1000
default_pool_size = 25
# redis.conf
maxmemory 4gb
maxmemory-policy allkeys-lru

# Enable AOF persistence
appendonly yes
appendfsync everysec
// Create indexes for memory collections
db.historial_pedidos.createIndex({ sessionId: 1, createdAt: -1 });
db.historial_clasificador.createIndex({ sessionId: 1, createdAt: -1 });

// Set TTL for automatic cleanup (30 days)
db.historial_pedidos.createIndex(
  { "createdAt": 1 },
  { expireAfterSeconds: 2592000 }
);

Monitoring & Observability

Application Monitoring

1

Enable n8n Metrics

N8N_METRICS=true
N8N_METRICS_INCLUDE_DEFAULT_METRICS=true
N8N_METRICS_INCLUDE_WORKFLOW_ID_LABEL=true
Access metrics at: http://localhost:5678/metrics
2

Configure Prometheus

# prometheus.yml
scrape_configs:
  - job_name: 'n8n'
    static_configs:
      - targets: ['n8n:5678']
    metrics_path: '/metrics'
3

Setup Grafana Dashboards

Key metrics to monitor:
  • Workflow execution count
  • Execution duration
  • Error rate
  • Webhook response times
  • Database connection pool usage

Error Tracking

The workflows include error notification via WhatsApp:
From Workflow Notes: “El ‘Gateaway’ está conectado a un Error Workflow (to notify when this one errors) conectado a mi teléfono de WhatsApp personal.”
Setup Error Workflow:
  1. Create a dedicated error workflow
  2. Use Error Trigger node
  3. Add WhatsApp node with your notification number
  4. Link both main workflows to this error workflow

Log Management

# Docker Compose logging
services:
  n8n:
    logging:
      driver: "json-file"
      options:
        max-size: "100m"
        max-file: "10"
Centralized Logging:
  • Use ELK Stack (Elasticsearch, Logstash, Kibana)
  • Or cloud solutions: CloudWatch, Stackdriver, Datadog

Backup & Disaster Recovery

Automated Backups

#!/bin/bash
# backup-postgres.sh

BACKUP_DIR="/backups/postgres"
DATE=$(date +%Y%m%d_%H%M%S)
FILE="$BACKUP_DIR/picanteria_db_$DATE.sql.gz"

# Create backup
pg_dump -h $POSTGRES_HOST -U $POSTGRES_USER picanteria_db | gzip > $FILE

# Upload to S3
aws s3 cp $FILE s3://your-bucket/backups/postgres/

# Cleanup old backups (keep 30 days)
find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete
Cron Schedule:
0 2 * * * /usr/local/bin/backup-postgres.sh

Disaster Recovery Plan

1

Document Recovery Procedures

Create runbook with:
  • RTO (Recovery Time Objective): 1 hour
  • RPO (Recovery Point Objective): 24 hours
  • Step-by-step restoration process
  • Contact information for team
2

Test Recovery Regularly

Monthly drill:
  1. Restore backups to staging environment
  2. Verify data integrity
  3. Test workflow execution
  4. Document any issues
3

Maintain Hot Standby

For critical deployments:
  • Secondary n8n instance (passive)
  • Database read replicas
  • Automated failover scripts

Performance Optimization

Workflow Optimization

The Receptor workflow uses Redis buffering:
  • Buffer window: 8 seconds
  • Purpose: Aggregate rapid messages
  • TTL: 30 seconds
This prevents message fragmentation and reduces AI API calls.
The Procesador workflow queries are optimized:
-- Uses TRIM for accurate matching
WHERE TRIM(telefono) = TRIM('...')

-- Filters inactive orders
AND estado_pedido NOT IN ('entregado', 'cancelado')

-- Limits results
LIMIT 1
Optimized per agent:
  • Orders: 25 messages (detailed history)
  • Reservations: 15 messages
  • General: 10 messages (fast queries)

API Rate Limiting

Google Gemini:
  • Free tier: 60 requests/minute
  • Implement exponential backoff
  • Use faster models for classification
WhatsApp Business:
  • Tier 1: 1,000 messages/day
  • Tier 2: 10,000 messages/day
  • Monitor usage in Meta dashboard

Deployment Process

Blue-Green Deployment

1

Prepare Blue environment

# Deploy to blue environment
docker-compose -f docker-compose.blue.yml up -d

# Verify health
curl https://blue.your-domain.com/healthz
2

Run smoke tests

  • Test webhook verification
  • Send test message
  • Verify database connections
  • Check AI agent responses
3

Switch traffic

Update load balancer to route to blue environment:
# Caddy
your-domain.com {
    reverse_proxy blue:5678
}
4

Monitor and rollback if needed

  • Watch error rates for 30 minutes
  • If issues detected, revert to green
  • Fix issues and retry

Production Checklist

Before going live:

Security

  • SSL certificates installed and valid
  • All default passwords changed
  • Firewall rules configured
  • Database connections use SSL/TLS
  • Row Level Security enabled on PostgreSQL
  • API tokens rotated and secured
  • Error notifications configured

Infrastructure

  • Reverse proxy (Caddy) configured
  • Health checks enabled
  • Auto-restart policies set
  • Resource limits configured
  • Backup system automated
  • Monitoring dashboards created

Application

  • Both workflows imported and activated
  • All credentials configured in n8n
  • WhatsApp webhook verified with Meta
  • Database schema migrated
  • Redis connection tested
  • AI models responding correctly

Testing

  • End-to-end message flow tested
  • Order creation verified
  • Database writes confirmed
  • Error handling validated
  • Load testing completed
  • Failover procedures tested

Documentation

  • Runbooks created for operations team
  • Disaster recovery plan documented
  • Escalation procedures defined
  • Architecture diagrams updated

Maintenance Windows

Planned Maintenance

Schedule:
  • Weekly: Database optimization (5 minutes)
  • Monthly: Security updates (30 minutes)
  • Quarterly: Major version upgrades (2 hours)
Notification:
  • Announce 48 hours in advance
  • Use low-traffic windows (3-5 AM local time)
  • Post status updates during maintenance

Support & Escalation

On-Call Rotation

Tier 1: Automated Alerts
  • Error workflow sends WhatsApp notifications
  • Monitoring alerts via email/SMS
Tier 2: Human Response
  • Review logs and metrics
  • Apply standard troubleshooting
  • Escalate if unresolved in 30 minutes
Tier 3: Engineering Team
  • Deep investigation
  • Code fixes if needed
  • Post-mortem after resolution

Post-Deployment

Monitoring Dashboard

Set up Grafana with key metrics

Troubleshooting Guide

Common issues and solutions

Database Schema

Reference for database structure

API Reference

Internal API documentation

Additional Resources