SiamCafe.net Blog
Technology

WordPress Block Theme Capacity Planning

wordpress block theme capacity planning
WordPress Block Theme Capacity Planning | SiamCafe Blog
2025-06-22· อ. บอม — SiamCafe.net· 988 คำ

WordPress Block Theme Capacity Planning คืออะไร

WordPress Block Theme คือ theme รุ่นใหม่ที่ใช้ Full Site Editing (FSE) ด้วย block-based templates แทน PHP templates แบบเดิม Capacity Planning คือการวางแผนทรัพยากร server (CPU, RAM, storage, bandwidth) ให้เพียงพอรองรับ traffic และ content ของเว็บไซต์ การรวมสองแนวคิดนี้ช่วยให้ WordPress sites ที่ใช้ Block Theme ทำงานได้เร็ว รองรับ traffic สูง ไม่ล่มเมื่อมี viral content และประหยัดค่าใช้จ่ายด้วยการจัดสรร resources อย่างเหมาะสม

Block Theme Architecture

# block_theme.py — WordPress Block Theme architecture
import json

class BlockThemeArch:
    COMPONENTS = {
        "templates": {
            "name": "Block Templates (HTML)",
            "description": "Templates เขียนด้วย HTML + Block markup แทน PHP",
            "files": "templates/index.html, templates/single.html, templates/archive.html",
            "impact": "เร็วกว่า PHP templates (less server processing)",
        },
        "template_parts": {
            "name": "Template Parts",
            "description": "ส่วนที่ reuse ได้ เช่น header, footer, sidebar",
            "files": "parts/header.html, parts/footer.html",
            "impact": "ลด code duplication",
        },
        "theme_json": {
            "name": "theme.json",
            "description": "Global styles, typography, colors, spacing ทั้ง theme",
            "files": "theme.json (root directory)",
            "impact": "Centralized design system, less CSS",
        },
        "patterns": {
            "name": "Block Patterns",
            "description": "Pre-designed block layouts ที่ reuse ได้",
            "files": "patterns/*.php",
            "impact": "เร็วขึ้นในการสร้าง content",
        },
    }

    PERFORMANCE_DIFF = {
        "classic_theme": {
            "name": "Classic Theme (PHP)",
            "ttfb": "200-500ms",
            "render": "ใช้ PHP render ทุก request",
            "caching": "ต้อง full-page cache",
        },
        "block_theme": {
            "name": "Block Theme (FSE)",
            "ttfb": "150-400ms",
            "render": "HTML templates + minimal PHP",
            "caching": "Cache-friendly, less dynamic content",
        },
    }

    def show_components(self):
        print("=== Block Theme Components ===\n")
        for key, comp in self.COMPONENTS.items():
            print(f"[{comp['name']}]")
            print(f"  {comp['description']}")
            print(f"  Impact: {comp['impact']}")
            print()

    def show_performance(self):
        print("=== Classic vs Block Theme ===")
        for key, theme in self.PERFORMANCE_DIFF.items():
            print(f"  [{theme['name']}] TTFB: {theme['ttfb']} | {theme['render']}")

arch = BlockThemeArch()
arch.show_components()
arch.show_performance()

Capacity Planning Framework

# capacity.py — WordPress capacity planning
import json
import random

class CapacityPlanning:
    TIERS = {
        "small": {
            "name": "Small (Blog/Portfolio)",
            "traffic": "< 10K visitors/month",
            "resources": {"cpu": "1-2 vCPU", "ram": "2-4 GB", "storage": "20-50 GB SSD", "bandwidth": "100 GB/month"},
            "hosting": "Shared hosting / Small VPS",
            "cost": "100-500 บาท/เดือน",
        },
        "medium": {
            "name": "Medium (Business/WooCommerce)",
            "traffic": "10K-100K visitors/month",
            "resources": {"cpu": "2-4 vCPU", "ram": "4-8 GB", "storage": "50-200 GB SSD", "bandwidth": "500 GB/month"},
            "hosting": "VPS / Managed WordPress",
            "cost": "500-3,000 บาท/เดือน",
        },
        "large": {
            "name": "Large (High-Traffic/Enterprise)",
            "traffic": "100K-1M+ visitors/month",
            "resources": {"cpu": "4-16 vCPU", "ram": "8-32 GB", "storage": "200 GB+ NVMe", "bandwidth": "2 TB+/month"},
            "hosting": "Dedicated / Cloud (AWS, GCP)",
            "cost": "3,000-30,000+ บาท/เดือน",
        },
    }

    CALCULATOR = """
# wp_capacity_calc.py — WordPress capacity calculator
class WPCapacityCalculator:
    def __init__(self):
        self.php_memory_per_request = 64  # MB
        self.max_execution_time = 30  # seconds
        self.avg_response_time = 0.5  # seconds
    
    def calculate(self, monthly_visitors, peak_multiplier=3):
        daily = monthly_visitors / 30
        hourly_peak = (daily / 24) * peak_multiplier
        requests_per_second = hourly_peak / 3600
        
        # PHP workers needed
        php_workers = max(4, int(requests_per_second / (1 / self.avg_response_time)))
        
        # RAM needed
        ram_php = php_workers * self.php_memory_per_request
        ram_mysql = max(512, monthly_visitors // 10000 * 256)
        ram_os = 512
        total_ram_mb = ram_php + ram_mysql + ram_os
        
        # CPU estimate
        cpu_cores = max(1, php_workers // 4)
        
        return {
            'monthly_visitors': monthly_visitors,
            'peak_rps': round(requests_per_second, 1),
            'php_workers': php_workers,
            'ram_mb': total_ram_mb,
            'ram_gb': round(total_ram_mb / 1024, 1),
            'cpu_cores': cpu_cores,
        }

calc = WPCapacityCalculator()
for visitors in [5000, 50000, 500000]:
    result = calc.calculate(visitors)
    print(f"  {visitors:>10} visitors/mo → "
          f"CPU: {result['cpu_cores']} cores, "
          f"RAM: {result['ram_gb']} GB, "
          f"Workers: {result['php_workers']}")
"""

    def show_tiers(self):
        print("=== Capacity Tiers ===\n")
        for key, tier in self.TIERS.items():
            print(f"[{tier['name']}] {tier['traffic']}")
            print(f"  Resources: {tier['resources']['cpu']}, {tier['resources']['ram']}")
            print(f"  Hosting: {tier['hosting']} | Cost: {tier['cost']}")
            print()

    def show_calculator(self):
        print("=== Capacity Calculator ===")
        print(self.CALCULATOR[:600])

cap = CapacityPlanning()
cap.show_tiers()
cap.show_calculator()

Performance Optimization

# optimization.py — WordPress performance optimization
import json

class WPOptimization:
    LAYERS = {
        "server": {
            "name": "Server Level",
            "optimizations": [
                "PHP 8.2+ (30-50% faster than PHP 7.4)",
                "OPcache enabled (cache compiled PHP)",
                "MySQL/MariaDB tuning (innodb_buffer_pool_size = 70% RAM)",
                "HTTP/2 or HTTP/3 enabled",
                "Gzip/Brotli compression",
            ],
        },
        "caching": {
            "name": "Caching Layer",
            "optimizations": [
                "Object Cache: Redis/Memcached (reduce DB queries)",
                "Page Cache: WP Super Cache / W3 Total Cache / LiteSpeed Cache",
                "CDN: Cloudflare / BunnyCDN (cache static assets globally)",
                "Browser Cache: Cache-Control headers (1 year for static)",
                "Varnish/Nginx FastCGI Cache (full-page cache at server level)",
            ],
        },
        "wordpress": {
            "name": "WordPress Level",
            "optimizations": [
                "ลด plugins (ใช้เท่าที่จำเป็น < 20 active plugins)",
                "Image optimization: WebP format, lazy loading",
                "Database cleanup: WP-Optimize, ลบ revisions/transients",
                "Disable unused features: XML-RPC, embeds, emojis",
                "Use block theme (faster than classic themes)",
            ],
        },
        "frontend": {
            "name": "Frontend Level",
            "optimizations": [
                "Critical CSS inline",
                "Defer non-critical JS",
                "Preload key resources (fonts, LCP image)",
                "Minimize DOM size (< 1500 elements)",
                "Core Web Vitals optimization (LCP < 2.5s, CLS < 0.1)",
            ],
        },
    }

    NGINX_CONFIG = """
# nginx.conf — WordPress optimization
server {
    listen 443 ssl http2;
    server_name example.com;
    root /var/www/html;
    
    # FastCGI Cache
    fastcgi_cache_path /tmp/nginx-cache levels=1:2
        keys_zone=WORDPRESS:100m inactive=60m max_size=1g;
    
    # Gzip
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1000;
    
    # Browser Cache
    location ~* \\.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # PHP-FPM
    location ~ \\.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_cache WORDPRESS;
        fastcgi_cache_valid 200 60m;
    }
}
"""

    def show_layers(self):
        print("=== Optimization Layers ===\n")
        for key, layer in self.LAYERS.items():
            print(f"[{layer['name']}]")
            for opt in layer["optimizations"][:3]:
                print(f"  • {opt}")
            print()

    def show_nginx(self):
        print("=== Nginx Config ===")
        print(self.NGINX_CONFIG[:500])

opt = WPOptimization()
opt.show_layers()
opt.show_nginx()

Load Testing

# load_test.py — WordPress load testing
import json
import random

class LoadTesting:
    TOOLS = {
        "k6": {"name": "k6 (Grafana)", "type": "Script-based", "command": "k6 run load-test.js"},
        "ab": {"name": "Apache Bench (ab)", "type": "Simple HTTP", "command": "ab -n 1000 -c 50 https://example.com/"},
        "siege": {"name": "Siege", "type": "HTTP regression", "command": "siege -c 50 -t 60S https://example.com/"},
        "locust": {"name": "Locust (Python)", "type": "Distributed", "command": "locust -f locustfile.py"},
    }

    K6_SCRIPT = """
# load-test.js — k6 load test for WordPress
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
    stages: [
        { duration: '2m', target: 50 },   // ramp up
        { duration: '5m', target: 50 },   // steady
        { duration: '2m', target: 100 },  // peak
        { duration: '5m', target: 100 },  // sustained peak
        { duration: '2m', target: 0 },    // ramp down
    ],
    thresholds: {
        http_req_duration: ['p(95)<500'],  // 95% < 500ms
        http_req_failed: ['rate<0.01'],    // < 1% errors
    },
};

export default function () {
    // Homepage
    let res = http.get('https://example.com/');
    check(res, { 'homepage 200': (r) => r.status === 200 });
    sleep(1);
    
    // Blog post
    res = http.get('https://example.com/sample-post/');
    check(res, { 'post 200': (r) => r.status === 200 });
    sleep(2);
}
"""

    def show_tools(self):
        print("=== Load Testing Tools ===\n")
        for key, tool in self.TOOLS.items():
            print(f"  [{tool['name']}] {tool['type']}: {tool['command']}")

    def show_k6(self):
        print(f"\n=== k6 Script ===")
        print(self.K6_SCRIPT[:500])

    def simulate_results(self):
        print(f"\n=== Load Test Results ===")
        results = {
            "Total requests": f"{random.randint(5000, 20000):,}",
            "Requests/sec": f"{random.randint(50, 200)}",
            "Avg response time": f"{random.randint(100, 400)}ms",
            "P95 response time": f"{random.randint(300, 800)}ms",
            "Error rate": f"{random.uniform(0, 2):.2f}%",
            "Max concurrent": random.randint(50, 200),
        }
        for m, v in results.items():
            print(f"  {m}: {v}")

lt = LoadTesting()
lt.show_tools()
lt.show_k6()
lt.simulate_results()

Monitoring & Alerts

# monitoring.py — WordPress monitoring
import json
import random

class WPMonitoring:
    METRICS = {
        "uptime": {"name": "Uptime", "tool": "Uptime Kuma / Pingdom", "threshold": "> 99.9%"},
        "ttfb": {"name": "TTFB (Time to First Byte)", "tool": "WebPageTest / Lighthouse", "threshold": "< 200ms"},
        "response_time": {"name": "Response Time", "tool": "New Relic / Datadog", "threshold": "< 500ms (P95)"},
        "cpu": {"name": "CPU Usage", "tool": "Prometheus + Node Exporter", "threshold": "< 70%"},
        "ram": {"name": "RAM Usage", "tool": "Prometheus + Node Exporter", "threshold": "< 80%"},
        "disk_io": {"name": "Disk I/O", "tool": "iostat / Prometheus", "threshold": "< 80% utilization"},
        "db_queries": {"name": "DB Queries/Page", "tool": "Query Monitor plugin", "threshold": "< 50 queries"},
        "php_workers": {"name": "PHP-FPM Workers", "tool": "php-fpm status page", "threshold": "< 80% active"},
    }

    def show_metrics(self):
        print("=== Key Metrics ===\n")
        for key, metric in self.METRICS.items():
            print(f"  [{metric['name']}] Tool: {metric['tool']} | Target: {metric['threshold']}")

    def dashboard(self):
        print(f"\n=== Live Dashboard ===")
        metrics = {
            "Uptime": f"{random.uniform(99.8, 99.99):.2f}%",
            "TTFB": f"{random.randint(100, 300)}ms",
            "CPU": f"{random.randint(20, 60)}%",
            "RAM": f"{random.randint(40, 75)}%",
            "PHP Workers": f"{random.randint(3, 12)}/16 active",
            "Cache Hit Rate": f"{random.randint(85, 99)}%",
        }
        for m, v in metrics.items():
            print(f"  {m}: {v}")

mon = WPMonitoring()
mon.show_metrics()
mon.dashboard()

การนำไปใช้งานจริงในองค์กร

สำหรับองค์กรขนาดกลางถึงใหญ่ แนะนำให้ใช้หลัก Three-Tier Architecture คือ Core Layer ที่เป็นแกนกลางของระบบ Distribution Layer ที่ทำหน้าที่กระจาย Traffic และ Access Layer ที่เชื่อมต่อกับผู้ใช้โดยตรง การแบ่ง Layer ชัดเจนช่วยให้การ Troubleshoot ง่ายขึ้นและสามารถ Scale ระบบได้ตามความต้องการ

เรื่อง Network Security ก็สำคัญไม่แพ้กัน ควรติดตั้ง Next-Generation Firewall ที่สามารถ Deep Packet Inspection ได้ ใช้ Network Segmentation แยก VLAN สำหรับแต่ละแผนก ติดตั้ง IDS/IPS เพื่อตรวจจับการโจมตี และทำ Regular Security Audit อย่างน้อยปีละ 2 ครั้ง

เปรียบเทียบข้อดีและข้อเสีย

ข้อดีข้อเสีย
ประสิทธิภาพสูง ทำงานได้เร็วและแม่นยำ ลดเวลาทำงานซ้ำซ้อนต้องใช้เวลาเรียนรู้เบื้องต้นพอสมควร มี Learning Curve สูง
มี Community ขนาดใหญ่ มีคนช่วยเหลือและแหล่งเรียนรู้มากมายบางฟีเจอร์อาจยังไม่เสถียร หรือมีการเปลี่ยนแปลงบ่อยในเวอร์ชันใหม่
รองรับ Integration กับเครื่องมือและบริการอื่นได้หลากหลายต้นทุนอาจสูงสำหรับ Enterprise License หรือ Cloud Service
เป็น Open Source หรือมีเวอร์ชันฟรีให้เริ่มต้นใช้งานต้องการ Hardware หรือ Infrastructure ที่เพียงพอ

จากตารางเปรียบเทียบจะเห็นว่าข้อดีมีมากกว่าข้อเสียอย่างชัดเจน โดยเฉพาะในแง่ของประสิทธิภาพและความสามารถในการ Scale สำหรับข้อเสียส่วนใหญ่สามารถแก้ไขได้ด้วยการเรียนรู้อย่างเป็นระบบและวางแผนทรัพยากรให้เหมาะสม

FAQ - คำถามที่พบบ่อย

Q: Block Theme เร็วกว่า Classic Theme จริงไหม?

A: เร็วกว่าเล็กน้อย (5-15%) เพราะ HTML templates ใช้ PHP processing น้อยกว่า แต่ปัจจัยหลักคือ: hosting quality, caching, plugins, image optimization Block Theme + good hosting + caching = เร็วมาก Classic Theme + no cache = ช้า ไม่ว่าจะใช้ theme แบบไหน

Q: Shared hosting พอสำหรับ Block Theme ไหม?

A: พอสำหรับ: blog เล็กๆ < 5K visitors/month, ไม่มี WooCommerce ไม่พอสำหรับ: traffic > 10K/month, WooCommerce, membership site แนะนำ: เริ่ม VPS ตั้งแต่ 10K visitors (DigitalOcean, Vultr, Linode ราคาไม่แพง)

Q: CDN จำเป็นไหม?

A: จำเป็นมาก Cloudflare (free tier) ลด TTFB 30-50% สำหรับ international visitors Cache static assets (images, CSS, JS) ใกล้ผู้เข้าชม ป้องกัน DDoS เบื้องต้น แม้แต่เว็บเล็กก็ควรใช้ CDN (Cloudflare free = ไม่มีค่าใช้จ่าย)

Q: Redis Object Cache คุ้มไหม?

A: คุ้มมากสำหรับ: WooCommerce, membership sites, dynamic content ลด DB queries 50-80%, ลด TTFB 20-40% ไม่จำเป็นสำหรับ: static blog ที่ใช้ page cache อยู่แล้ว ราคา: Redis managed $5-15/month หรือ self-hosted ฟรี

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

WordPress Block Theme SaaS Architectureอ่านบทความ → WordPress Block Theme Agile Scrum Kanbanอ่านบทความ → WordPress Block Theme Service Mesh Setupอ่านบทความ → WordPress Block Theme Best Practices ที่ต้องรู้อ่านบทความ → WordPress Block Theme 12 Factor Appอ่านบทความ →

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