SiamCafe.net Blog
Technology

WordPress WooCommerce Message Queue Design ออกแบบระบบควสำหรับรานคาออนไลน

wordpress woocommerce message queue design
WordPress WooCommerce Message Queue Design | SiamCafe Blog
2025-11-20· อ. บอม — SiamCafe.net· 1,076 คำ

Message Queue ?????????????????? WooCommerce ?????????????????????

Message Queue ????????????????????????????????????????????????????????????????????????????????? WooCommerce ?????????????????????????????? ????????? asynchronous ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???????????? ????????? email, update inventory, sync ????????? ERP, generate invoice, notify warehouse ??????????????????????????????????????? response ???????????????????????? ?????????????????????????????????????????????

???????????????????????? WooCommerce ???????????????????????? message queue ????????????????????????????????????????????????????????? WordPress ???????????????????????????????????????????????? 1 request ????????? email confirmation (2-5 ??????????????????), update stock (0.5 ??????????????????), call payment gateway (1-3 ??????????????????), sync ERP (2-5 ??????????????????), generate PDF invoice (1-2 ??????????????????) ????????? 7-16 ?????????????????? ????????????????????????????????? ????????? timeout

Message Queue ?????????????????????????????????????????? ??????????????????????????????????????? WordPress ??????????????????????????? order ???????????? push ????????????????????? queue (< 1 ??????????????????) ?????????????????????????????????????????? thank you ??????????????? ???????????????????????? ????????? process ?????? background ????????? workers ?????????????????????????????? ??????????????????????????? fail retry ??????????????????????????? ???????????????????????? user experience

????????????????????? Message Queue ?????????????????? WordPress

Setup Redis queue ?????????????????? WooCommerce

# === Message Queue Setup for WooCommerce ===

# 1. Install Redis
sudo apt install -y redis-server

# Configure Redis
cat > /etc/redis/redis.conf << 'EOF'
bind 127.0.0.1
port 6379
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000
appendonly yes
appendfsync everysec
EOF

sudo systemctl enable --now redis-server

# 2. Install Redis PHP Extension
sudo apt install -y php8.3-redis
sudo systemctl restart php8.3-fpm

# 3. Install WP-CLI
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

# 4. Install Redis Object Cache Plugin
wp plugin install redis-cache --activate --path=/var/www/html

# Configure wp-config.php
cat >> /var/www/html/wp-config.php << 'PHP'

/* Redis Configuration */
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_PREFIX', 'woo_');
PHP

# Enable Redis object cache
wp redis enable --path=/var/www/html

# 5. Install Action Scheduler (built into WooCommerce)
# WooCommerce uses Action Scheduler for background jobs
# Verify it's working:
wp action-scheduler list --status=pending --path=/var/www/html

# 6. Queue Worker (WP-Cron alternative)
# Disable WP-Cron (use system cron instead)
# Add to wp-config.php:
# define('DISABLE_WP_CRON', true);

# System cron (runs every minute)
echo "* * * * * www-data cd /var/www/html && wp cron event run --due-now --quiet" | \
  sudo tee /etc/cron.d/wp-cron

# Action Scheduler worker (process queue jobs)
echo "* * * * * www-data cd /var/www/html && wp action-scheduler run --batch-size=25 --quiet" | \
  sudo tee /etc/cron.d/woo-queue

echo "Message queue setup complete"

?????????????????? Queue Architecture

Architecture ?????????????????? WooCommerce message queue

#!/usr/bin/env python3
# queue_architecture.py ??? WooCommerce Queue Architecture
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("architecture")

class WooCommerceQueueArchitecture:
    def __init__(self):
        self.queues = {}
    
    def architecture_design(self):
        return {
            "flow": [
                "1. Customer places order ??? WooCommerce saves order to DB",
                "2. woocommerce_checkout_order_processed hook fires",
                "3. Queue dispatcher pushes jobs to different queues",
                "4. Workers process jobs asynchronously",
                "5. Results stored, notifications sent",
            ],
            "queues": {
                "high_priority": {
                    "jobs": ["payment_capture", "stock_reduction", "order_confirmation_email"],
                    "max_delay": "30 seconds",
                    "workers": 3,
                    "retry": 5,
                },
                "medium_priority": {
                    "jobs": ["erp_sync", "invoice_generation", "shipping_label"],
                    "max_delay": "5 minutes",
                    "workers": 2,
                    "retry": 3,
                },
                "low_priority": {
                    "jobs": ["analytics_tracking", "crm_update", "review_request_email"],
                    "max_delay": "30 minutes",
                    "workers": 1,
                    "retry": 2,
                },
                "bulk_operations": {
                    "jobs": ["price_update", "stock_sync", "product_import"],
                    "max_delay": "1 hour",
                    "workers": 1,
                    "retry": 1,
                },
            },
            "error_handling": {
                "retry_strategy": "Exponential backoff (1s, 2s, 4s, 8s, 16s)",
                "dead_letter_queue": "Failed jobs after max retries ??? DLQ for manual review",
                "alerting": "Slack notification when DLQ count > 10",
                "monitoring": "Queue depth, processing time, error rate",
            },
        }
    
    def job_types(self):
        return {
            "send_order_email": {
                "queue": "high_priority",
                "payload": {"order_id": "int", "email_type": "string"},
                "timeout": 30,
                "retry": 3,
            },
            "sync_erp": {
                "queue": "medium_priority",
                "payload": {"order_id": "int", "erp_endpoint": "string"},
                "timeout": 60,
                "retry": 5,
            },
            "generate_invoice_pdf": {
                "queue": "medium_priority",
                "payload": {"order_id": "int", "template": "string"},
                "timeout": 30,
                "retry": 2,
            },
            "update_analytics": {
                "queue": "low_priority",
                "payload": {"order_id": "int", "event": "string"},
                "timeout": 15,
                "retry": 1,
            },
        }

arch = WooCommerceQueueArchitecture()
design = arch.architecture_design()
print("Queue Architecture:")
for queue, config in design["queues"].items():
    print(f"\n  {queue}:")
    print(f"    Jobs: {', '.join(config['jobs'])}")
    print(f"    Workers: {config['workers']}, Max delay: {config['max_delay']}")

Implement Queue Workers

??????????????? queue workers ?????????????????? WooCommerce

# === WooCommerce Queue Workers (PHP Plugin) ===

cat > wp-content/plugins/woo-queue/woo-queue.php << 'PHPEOF'
 $order_id,
            'type' => 'customer_processing_order'
        ], 'woo-high-priority');
        
        // Medium priority: Sync to ERP (delay 60s)
        as_schedule_single_action(time() + 60, 'woo_queue_sync_erp', [
            'order_id' => $order_id
        ], 'woo-medium-priority');
        
        // Medium priority: Generate invoice PDF
        as_schedule_single_action(time() + 120, 'woo_queue_generate_invoice', [
            'order_id' => $order_id
        ], 'woo-medium-priority');
        
        // Low priority: Update analytics (delay 5min)
        as_schedule_single_action(time() + 300, 'woo_queue_update_analytics', [
            'order_id' => $order_id
        ], 'woo-low-priority');
        
        // Log dispatch
        wc_get_logger()->info("Order #{$order_id}: 4 jobs dispatched to queue", [
            'source' => 'woo-queue'
        ]);
    }
    
    public function process_email($order_id, $type) {
        $order = wc_get_order($order_id);
        if (!$order) return;
        
        WC()->mailer()->get_emails()[$type]->trigger($order_id);
        
        wc_get_logger()->info("Email sent: {$type} for order #{$order_id}", [
            'source' => 'woo-queue'
        ]);
    }
    
    public function process_erp_sync($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) return;
        
        // ERP sync logic here
        $erp_data = [
            'order_number' => $order->get_order_number(),
            'total' => $order->get_total(),
            'items' => [],
        ];
        
        foreach ($order->get_items() as $item) {
            $erp_data['items'][] = [
                'sku' => $item->get_product()->get_sku(),
                'qty' => $item->get_quantity(),
                'total' => $item->get_total(),
            ];
        }
        
        // wp_remote_post($erp_endpoint, ['body' => json_encode($erp_data)]);
        
        wc_get_logger()->info("ERP synced for order #{$order_id}", [
            'source' => 'woo-queue'
        ]);
    }
    
    public function process_invoice($order_id) {
        // Generate PDF invoice
        wc_get_logger()->info("Invoice generated for order #{$order_id}", [
            'source' => 'woo-queue'
        ]);
    }
    
    public function process_analytics($order_id) {
        // Send to analytics
        wc_get_logger()->info("Analytics updated for order #{$order_id}", [
            'source' => 'woo-queue'
        ]);
    }
}

WooQueue::init();
PHPEOF

echo "WooCommerce queue plugin created"

Order Processing Pipeline

??????????????? order processing pipeline ??????????????????????????????

#!/usr/bin/env python3
# order_pipeline.py ??? WooCommerce Order Processing Pipeline
import json
import logging
import time
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("pipeline")

class OrderPipeline:
    def __init__(self):
        self.stages = []
        self.results = {}
    
    def define_pipeline(self):
        return {
            "stages": [
                {
                    "name": "Payment Verification",
                    "queue": "high_priority",
                    "timeout": 30,
                    "actions": [
                        "Verify payment status with gateway",
                        "Update order status to 'processing'",
                        "Reserve stock",
                    ],
                },
                {
                    "name": "Notification",
                    "queue": "high_priority",
                    "timeout": 30,
                    "actions": [
                        "Send customer confirmation email",
                        "Send admin new order email",
                        "Push notification (mobile app)",
                    ],
                },
                {
                    "name": "Fulfillment",
                    "queue": "medium_priority",
                    "timeout": 120,
                    "actions": [
                        "Sync order to warehouse system",
                        "Generate shipping label",
                        "Update shipping status",
                    ],
                },
                {
                    "name": "Accounting",
                    "queue": "medium_priority",
                    "timeout": 60,
                    "actions": [
                        "Generate invoice PDF",
                        "Sync to accounting software",
                        "Update tax records",
                    ],
                },
                {
                    "name": "Post-Order",
                    "queue": "low_priority",
                    "timeout": 300,
                    "actions": [
                        "Update CRM",
                        "Track analytics event",
                        "Schedule review request (7 days)",
                        "Update loyalty points",
                    ],
                },
            ],
            "performance_comparison": {
                "without_queue": {
                    "checkout_time": "7-16 seconds",
                    "user_experience": "Slow, may timeout",
                    "error_handling": "Fails silently, data inconsistency",
                    "scalability": "Poor under load",
                },
                "with_queue": {
                    "checkout_time": "< 1 second",
                    "user_experience": "Fast, responsive",
                    "error_handling": "Auto retry, dead letter queue",
                    "scalability": "Add workers as needed",
                },
            },
        }
    
    def simulate_order(self, order_id):
        pipeline = self.define_pipeline()
        results = []
        
        for stage in pipeline["stages"]:
            start = time.time()
            # Simulate processing
            time.sleep(0.01)
            elapsed = time.time() - start
            
            results.append({
                "stage": stage["name"],
                "queue": stage["queue"],
                "actions": len(stage["actions"]),
                "status": "completed",
                "time_ms": round(elapsed * 1000, 1),
            })
        
        return {
            "order_id": order_id,
            "stages_completed": len(results),
            "total_time_ms": sum(r["time_ms"] for r in results),
            "results": results,
        }

pipeline = OrderPipeline()
design = pipeline.define_pipeline()
print("Order Pipeline:")
for stage in design["stages"]:
    print(f"  {stage['name']}: {len(stage['actions'])} actions ({stage['queue']})")

print("\nPerformance:")
for mode, perf in design["performance_comparison"].items():
    print(f"  {mode}: {perf['checkout_time']}")

Monitoring ????????? Scaling

Monitor queue health ????????? scale workers

# === Queue Monitoring & Scaling ===

# 1. Monitor Action Scheduler Queue
cat > monitor_queue.sh << 'BASH'
#!/bin/bash
# WooCommerce Queue Monitor

WP_PATH="/var/www/html"

echo "=== WooCommerce Queue Status ==="
echo ""

# Pending jobs
PENDING=$(wp action-scheduler list --status=pending --format=count --path=$WP_PATH 2>/dev/null)
echo "Pending jobs: $PENDING"

# Running jobs
RUNNING=$(wp action-scheduler list --status=in-progress --format=count --path=$WP_PATH 2>/dev/null)
echo "Running jobs: $RUNNING"

# Failed jobs
FAILED=$(wp action-scheduler list --status=failed --format=count --path=$WP_PATH 2>/dev/null)
echo "Failed jobs: $FAILED"

# Completed today
COMPLETED=$(wp action-scheduler list --status=complete --format=count --path=$WP_PATH 2>/dev/null)
echo "Completed: $COMPLETED"

echo ""
echo "=== Redis Status ==="
redis-cli info memory | grep used_memory_human
redis-cli info keyspace

echo ""
echo "=== Queue Health ==="
if [ "$FAILED" -gt 10 ]; then
    echo "WARNING: $FAILED failed jobs!"
fi
if [ "$PENDING" -gt 100 ]; then
    echo "WARNING: Queue backlog! $PENDING pending jobs"
fi

echo ""
echo "=== Recent Errors ==="
wp action-scheduler list --status=failed --per-page=5 --format=table --path=$WP_PATH 2>/dev/null
BASH
chmod +x monitor_queue.sh

# 2. Prometheus Metrics Exporter
cat > queue_metrics.php << 'PHP'
 'GET',
        'callback' => function() {
            global $wpdb;
            
            $table = $wpdb->prefix . 'actionscheduler_actions';
            $stats = $wpdb->get_results("
                SELECT status, COUNT(*) as count 
                FROM {$table} 
                GROUP BY status
            ", ARRAY_A);
            
            $output = "# HELP woo_queue_jobs WooCommerce queue jobs by status\n";
            $output .= "# TYPE woo_queue_jobs gauge\n";
            foreach ($stats as $stat) {
                $output .= "woo_queue_jobs{status=\"{$stat['status']}\"} {$stat['count']}\n";
            }
            
            return new WP_REST_Response($output, 200, [
                'Content-Type' => 'text/plain'
            ]);
        },
        'permission_callback' => '__return_true',
    ]);
});
PHP

# 3. Scaling Workers
# Add more cron jobs for high-traffic periods
cat > /etc/cron.d/woo-queue-scale << 'EOF'
# Normal: process every minute
* * * * * www-data cd /var/www/html && wp action-scheduler run --batch-size=25 --quiet

# Peak hours (9am-9pm): process every 30 seconds
* 9-21 * * * www-data sleep 30 && cd /var/www/html && wp action-scheduler run --batch-size=25 --quiet
EOF

echo "Monitoring and scaling configured"

FAQ ??????????????????????????????????????????

Q: WooCommerce ?????? queue ?????????????????????????

A: ?????? WooCommerce ????????? Action Scheduler library ??????????????? ???????????? job queue ????????????????????? jobs ?????? WordPress database ??????????????????????????? WP-Cron ???????????? system cron ?????????????????? scheduled actions, async actions, recurring actions ?????????????????? retry, logging, monitoring ???????????? WP Admin ??? Tools ??? Scheduled Actions ??????????????????????????????????????????????????????-???????????? Action Scheduler ????????????????????? ?????????????????????????????????????????????????????? (1000+ orders/?????????) ?????????????????????????????? Redis queue ???????????? RabbitMQ ??????????????? ??????????????? DB-based queue ?????? limitations ?????????????????? throughput

Q: ????????????????????????????????? WP-Cron ????????????????????? system cron?

A: WP-Cron ?????????????????????????????????????????? visit ???????????????????????? ?????????????????????????????????????????? cron ???????????????????????? ??????????????????????????????????????? cron ????????? fire ??????????????????????????????????????????????????? ??????????????????????????? timing System cron ????????????????????????????????????????????????????????? ?????????????????????????????? visitors ???????????????????????? overhead ????????? web requests ????????????????????????????????????????????? ???????????? ????????? WP-Cron ?????? wp-config.php define('DISABLE_WP_CRON', true) ??????????????????????????? system cron ????????????????????? ??????????????? queue processing ???????????????????????? ?????????????????????

Q: Redis ????????? Action Scheduler ??????????????????????????????????

A: Action Scheduler (DB-based) ??????????????? ????????????????????????????????????????????????????????????????????? built-in WooCommerce, ????????????, persist data ?????? DB, ?????? UI ?????? WP Admin ????????????????????? ????????????????????? Redis ??????????????? queue ????????????, DB lock issues ??????????????? concurrent access ????????? Redis ??????????????? ????????????????????? (in-memory), ?????????????????? concurrent access ??????, pub/sub ?????????????????? real-time notifications ????????????????????? ?????????????????????????????????????????? manage Redis server, data ??????????????????????????? Redis crash (????????? AOF persistence ??????????????????) ??????????????? ????????? Action Scheduler ???????????? ????????? pending jobs > 1000 ????????? processing ????????? ??????????????????????????? Redis

Q: Queue ???????????? performance WooCommerce ???????????????????????????????

A: ?????????????????????????????? Checkout time ??????????????? 7-16 ?????????????????? ??????????????? < 1 ?????????????????? (?????????????????????????????? thank you ???????????????) Server load ???????????? 30-50% ????????????????????????????????????????????????????????????????????? ???????????????????????????????????? checkout Conversion rate ??????????????? 10-25% ??????????????? checkout ???????????????????????? (????????? 1 ?????????????????????????????????????????? conversion ?????? 7%) Error handling ?????????????????? failed jobs retry ??????????????????????????? ????????????????????? Scalability ?????????????????? traffic spike ??????????????????????????? queue absorb load ?????????????????????????????????????????????????????????????????? plugins ?????????????????? server spec ????????? complexity ????????? order processing

📖 บทความที่เกี่ยวข้อง

WordPress WooCommerce สำหรับมือใหม่ Step by Stepอ่านบทความ → Ansible AWX Tower Message Queue Designอ่านบทความ → WordPress WooCommerce Cloud Migration Strategyอ่านบทความ → Linux io_uring Message Queue Designอ่านบทความ → MongoDB Aggregation Message Queue Designอ่านบทความ →

📚 ดูบทความทั้งหมด →