SiamCafe.net Blog
Technology

WordPress Block Theme Scaling Strategy วิธี Scale — ขยายระบบ WordPress

wordpress block theme scaling strategy วธ scale
WordPress Block Theme Scaling Strategy วิธี Scale | SiamCafe Blog
2025-11-11· อ. บอม — SiamCafe.net· 1,408 คำ

WordPress Block Theme คืออะไร

WordPress Block Theme (Full Site Editing Theme) เป็น theme รุ่นใหม่ที่ใช้ block editor (Gutenberg) ในการแก้ไขทุกส่วนของ website ตั้งแต่ header, footer, sidebar จนถึง templates ทั้งหมด แทนที่ classic theme ที่ต้องแก้ PHP files

Block Theme ใช้ HTML-based templates แทน PHP templates ทำให้ performance ดีขึ้น render เร็วกว่า classic themes ลด PHP processing time ส่งผลให้ scaling ง่ายขึ้นเพราะ server load ลดลง

Scaling Strategy สำหรับ WordPress Block Theme ครอบคลุม Horizontal Scaling เพิ่ม web servers ด้วย load balancer, Vertical Scaling เพิ่ม CPU/RAM ของ server, Database Scaling ใช้ read replicas และ query caching, Caching Strategy ใช้ page cache, object cache, CDN, Edge Computing deploy static assets ที่ edge network ทั่วโลก

ติดตั้งและสร้าง Block Theme

สร้าง Block Theme ตั้งแต่ต้น

# === WordPress Block Theme Setup ===

# 1. Create Block Theme Structure
mkdir -p my-block-theme/{parts, templates, patterns, styles, assets/{css, js, images}}

# 2. theme.json — Core Configuration
cat > my-block-theme/theme.json << 'EOF'
{
  "$schema": "https://schemas.wp.org/trunk/theme.json",
  "version": 2,
  "settings": {
    "appearanceTools": true,
    "color": {
      "palette": [
        { "slug": "primary", "color": "#2563eb", "name": "Primary" },
        { "slug": "secondary", "color": "#7c3aed", "name": "Secondary" },
        { "slug": "dark", "color": "#1e293b", "name": "Dark" },
        { "slug": "light", "color": "#f8fafc", "name": "Light" }
      ]
    },
    "typography": {
      "fontFamilies": [
        {
          "fontFamily": "Inter, system-ui, sans-serif",
          "name": "Inter",
          "slug": "inter"
        }
      ],
      "fontSizes": [
        { "slug": "small", "size": "0.875rem", "name": "Small" },
        { "slug": "medium", "size": "1rem", "name": "Medium" },
        { "slug": "large", "size": "1.25rem", "name": "Large" },
        { "slug": "x-large", "size": "2rem", "name": "Extra Large" }
      ]
    },
    "layout": {
      "contentSize": "800px",
      "wideSize": "1200px"
    },
    "spacing": {
      "units": ["px", "em", "rem", "%", "vw"]
    }
  },
  "styles": {
    "color": {
      "background": "var(--wp--preset--color--light)",
      "text": "var(--wp--preset--color--dark)"
    },
    "typography": {
      "fontFamily": "var(--wp--preset--font-family--inter)",
      "fontSize": "var(--wp--preset--font-size--medium)",
      "lineHeight": "1.75"
    }
  },
  "templateParts": [
    { "name": "header", "title": "Header", "area": "header" },
    { "name": "footer", "title": "Footer", "area": "footer" }
  ]
}
EOF

# 3. Header Template Part
cat > my-block-theme/parts/header.html << 'HTMLEOF'

HTMLEOF # 4. Index Template cat > my-block-theme/templates/index.html << 'HTMLEOF'
HTMLEOF # 5. style.css (required) cat > my-block-theme/style.css << 'EOF' /* Theme Name: My Block Theme Theme URI: https://example.com Author: Developer Description: High-performance block theme for scaling Version: 1.0.0 Requires at least: 6.4 Tested up to: 6.7 Requires PHP: 8.1 License: GPL-2.0-or-later */ EOF echo "Block theme created"

Scaling Strategy สำหรับ WordPress

วิธี scale WordPress สำหรับ traffic สูง

#!/usr/bin/env python3
# wp_scaling.py — WordPress Scaling Strategy
import json
import logging
from typing import Dict, List

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

class WordPressScalingPlanner:
    def __init__(self, current_traffic, target_traffic):
        self.current = current_traffic  # requests per second
        self.target = target_traffic
    
    def recommend_architecture(self):
        if self.target < 50:
            return self._single_server()
        elif self.target < 500:
            return self._multi_server()
        elif self.target < 5000:
            return self._distributed()
        else:
            return self._enterprise()
    
    def _single_server(self):
        return {
            "tier": "single_server",
            "traffic": f"< 50 req/s",
            "components": {
                "web": "1x 4 vCPU, 8GB RAM",
                "database": "MySQL on same server",
                "cache": "Redis (local)",
                "cdn": "Cloudflare Free",
            },
            "estimated_cost": "$20-50/month",
            "optimizations": [
                "Page caching (WP Super Cache)",
                "Redis object cache",
                "Image optimization",
                "Block theme (faster rendering)",
            ],
        }
    
    def _multi_server(self):
        return {
            "tier": "multi_server",
            "traffic": f"50-500 req/s",
            "components": {
                "load_balancer": "HAProxy or AWS ALB",
                "web": "2-4x 4 vCPU, 8GB RAM",
                "database": "Managed MySQL (RDS/CloudSQL)",
                "cache": "Redis Cluster (ElastiCache)",
                "cdn": "Cloudflare Pro or AWS CloudFront",
                "storage": "S3 for media files",
            },
            "estimated_cost": "$200-500/month",
            "optimizations": [
                "Full page cache at edge (Cloudflare APO)",
                "Redis object cache cluster",
                "Database read replicas",
                "Shared file system (EFS/NFS) for uploads",
                "Session storage in Redis",
            ],
        }
    
    def _distributed(self):
        return {
            "tier": "distributed",
            "traffic": f"500-5000 req/s",
            "components": {
                "load_balancer": "AWS ALB + WAF",
                "web": "Auto Scaling Group (4-20 instances)",
                "database": "Aurora MySQL with read replicas",
                "cache": "Redis Cluster (multi-node)",
                "cdn": "Cloudflare Enterprise or CloudFront",
                "storage": "S3 + CloudFront for all media",
                "search": "Elasticsearch for search",
            },
            "estimated_cost": "$1,000-5,000/month",
        }
    
    def _enterprise(self):
        return {
            "tier": "enterprise",
            "traffic": f"5000+ req/s",
            "components": {
                "load_balancer": "Multi-region ALB + Global Accelerator",
                "web": "Kubernetes (EKS) with HPA",
                "database": "Aurora Global Database",
                "cache": "Redis Cluster (multi-AZ)",
                "cdn": "Multi-CDN strategy",
                "storage": "S3 Cross-Region Replication",
            },
            "estimated_cost": "$5,000+/month",
        }
    
    def calculate_capacity(self, server_specs):
        vCPU = server_specs.get("vcpu", 4)
        ram_gb = server_specs.get("ram_gb", 8)
        
        # Rough WordPress capacity estimates
        without_cache = vCPU * 15  # ~15 req/s per vCPU (PHP)
        with_page_cache = vCPU * 500  # ~500 req/s per vCPU (cached)
        with_cdn = with_page_cache * 10  # CDN handles 90% of traffic
        
        return {
            "server": f"{vCPU} vCPU, {ram_gb}GB RAM",
            "capacity_no_cache": f"{without_cache} req/s",
            "capacity_page_cache": f"{with_page_cache} req/s",
            "capacity_with_cdn": f"{with_cdn} req/s",
            "recommendation": "Always use page cache + CDN",
        }

planner = WordPressScalingPlanner(current_traffic=30, target_traffic=200)
arch = planner.recommend_architecture()
print(json.dumps(arch, indent=2))

capacity = planner.calculate_capacity({"vcpu": 4, "ram_gb": 8})
print(json.dumps(capacity, indent=2))

Database และ Caching Optimization

Optimize database และ caching

# === Database & Caching Optimization ===

# 1. MySQL Optimization for WordPress
# ===================================
cat > my.cnf << 'EOF'
[mysqld]
# InnoDB Settings
innodb_buffer_pool_size = 4G
innodb_buffer_pool_instances = 4
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

# Query Cache (MySQL 5.7)
# query_cache_type = 1
# query_cache_size = 128M

# Connection Settings
max_connections = 500
wait_timeout = 300
interactive_timeout = 300

# Temp Tables
tmp_table_size = 256M
max_heap_table_size = 256M

# Thread Cache
thread_cache_size = 50

# Slow Query Log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
EOF

# 2. WordPress Database Optimization
# ===================================
cat > optimize_wp_db.sql << 'SQL'
-- Remove post revisions (keep last 5)
DELETE FROM wp_posts
WHERE post_type = 'revision'
AND ID NOT IN (
    SELECT * FROM (
        SELECT ID FROM wp_posts
        WHERE post_type = 'revision'
        ORDER BY post_date DESC
        LIMIT 5
    ) AS keep_revisions
);

-- Clean up transients
DELETE FROM wp_options WHERE option_name LIKE '%_transient_%';

-- Clean up orphaned postmeta
DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts p ON pm.post_id = p.ID
WHERE p.ID IS NULL;

-- Optimize tables
OPTIMIZE TABLE wp_posts;
OPTIMIZE TABLE wp_postmeta;
OPTIMIZE TABLE wp_options;
OPTIMIZE TABLE wp_comments;
OPTIMIZE TABLE wp_commentmeta;

-- Add useful indexes
ALTER TABLE wp_options ADD INDEX autoload_idx (autoload);
ALTER TABLE wp_postmeta ADD INDEX meta_value_idx (meta_value(191));
SQL

# 3. Redis Object Cache Configuration
# ===================================
# wp-config.php:
# define('WP_REDIS_HOST', '127.0.0.1');
# define('WP_REDIS_PORT', 6379);
# define('WP_REDIS_DATABASE', 0);
# define('WP_REDIS_MAXTTL', 86400);
# define('WP_REDIS_PREFIX', 'wp_');

# Install Redis Object Cache plugin
# wp plugin install redis-cache --activate
# wp redis enable

# 4. Page Cache with Nginx FastCGI Cache
# ===================================
cat >> /etc/nginx/nginx.conf << 'NGINXEOF'
# FastCGI Cache Zone
fastcgi_cache_path /var/cache/nginx levels=1:2
    keys_zone=wordpress:100m max_size=10g inactive=60m;

server {
    # Skip cache for logged-in users and POST requests
    set $skip_cache 0;
    
    if ($request_method = POST) { set $skip_cache 1; }
    if ($query_string != "") { set $skip_cache 1; }
    if ($http_cookie ~* "wordpress_logged_in") { set $skip_cache 1; }
    if ($http_cookie ~* "woocommerce_items_in_cart") { set $skip_cache 1; }
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php") { set $skip_cache 1; }
    
    location ~ \.php$ {
        fastcgi_cache wordpress;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        add_header X-Cache-Status $upstream_cache_status;
        
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
NGINXEOF

echo "Database and caching optimized"

CDN และ Edge Caching

ตั้งค่า CDN สำหรับ WordPress

# === CDN & Edge Setup ===

# 1. Cloudflare Configuration
# ===================================
# Page Rules:
# - *.example.com/wp-admin/* → Cache Level: Bypass
# - *.example.com/wp-login.php → Cache Level: Bypass, Security: High
# - *.example.com/wp-content/uploads/* → Cache Everything, Edge TTL: 1 month
# - *.example.com/* → Cache Everything, Edge TTL: 4 hours

# 2. Cloudflare APO (Automatic Platform Optimization)
# ===================================
# $5/month — caches entire WordPress pages at edge
# Benefits:
# - HTML pages cached at edge (not just static assets)
# - Automatic cache purge on content update
# - 90%+ cache hit rate for WordPress
# - TTFB < 100ms from edge

# 3. AWS CloudFront + S3 for Media
# ===================================
cat > cloudfront_config.json << 'EOF'
{
  "Origins": [
    {
      "Id": "wordpress-origin",
      "DomainName": "origin.example.com",
      "CustomOriginConfig": {
        "HTTPPort": 80,
        "HTTPSPort": 443,
        "OriginProtocolPolicy": "https-only"
      }
    },
    {
      "Id": "s3-media",
      "DomainName": "media-bucket.s3.amazonaws.com",
      "S3OriginConfig": {
        "OriginAccessIdentity": "origin-access-identity/cloudfront/XXXXX"
      }
    }
  ],
  "CacheBehaviors": [
    {
      "PathPattern": "/wp-content/uploads/*",
      "TargetOriginId": "s3-media",
      "ViewerProtocolPolicy": "redirect-to-https",
      "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
      "Compress": true
    }
  ],
  "DefaultCacheBehavior": {
    "TargetOriginId": "wordpress-origin",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "custom-wordpress-policy",
    "Compress": true
  }
}
EOF

# 4. Offload Media to S3
# ===================================
# Install WP Offload Media plugin
# wp plugin install amazon-s3-and-cloudfront --activate
#
# Configuration:
# - Bucket: media-bucket
# - Region: ap-southeast-1
# - CloudFront URL: https://cdn.example.com
# - Remove local files: Yes (save server storage)
# - Rewrite URLs: Yes

# 5. Performance Testing
# ===================================
# Test with Apache Bench
# ab -n 1000 -c 50 https://example.com/

# Test with k6
cat > loadtest.js << 'K6EOF'
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '30s', target: 50 },
    { duration: '1m', target: 100 },
    { duration: '30s', target: 200 },
    { duration: '1m', target: 200 },
    { duration: '30s', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.01'],
  },
};

export default function () {
  const pages = ['/', '/blog/', '/about/', '/contact/'];
  const page = pages[Math.floor(Math.random() * pages.length)];
  
  const res = http.get(`https://example.com`);
  check(res, {
    'status is 200': (r) => r.status === 200,
    'response time < 500ms': (r) => r.timings.duration < 500,
  });
  
  sleep(1);
}
K6EOF

# k6 run loadtest.js

echo "CDN and edge caching configured"

Monitoring และ Auto Scaling

Monitor และ auto scale WordPress

#!/usr/bin/env python3
# wp_monitor.py — WordPress Monitoring
import json
import logging
from datetime import datetime

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

class WordPressMonitor:
    def __init__(self):
        self.metrics = []
    
    def collect_metrics(self):
        return {
            "timestamp": datetime.utcnow().isoformat(),
            "performance": {
                "ttfb_ms": 85,
                "page_load_ms": 1200,
                "php_execution_ms": 150,
                "db_query_time_ms": 45,
                "cache_hit_rate_pct": 92,
            },
            "server": {
                "cpu_pct": 45,
                "memory_pct": 65,
                "disk_io_pct": 20,
                "active_connections": 85,
                "php_fpm_active": 12,
                "php_fpm_idle": 38,
            },
            "database": {
                "connections_active": 25,
                "slow_queries_per_min": 2,
                "queries_per_sec": 450,
                "innodb_buffer_hit_pct": 99.2,
            },
            "wordpress": {
                "active_plugins": 12,
                "db_queries_per_page": 35,
                "autoloaded_options_kb": 450,
                "cron_jobs_pending": 3,
            },
        }
    
    def check_health(self, metrics):
        issues = []
        
        if metrics["performance"]["ttfb_ms"] > 500:
            issues.append({"severity": "high", "issue": "TTFB too high", "value": metrics["performance"]["ttfb_ms"]})
        
        if metrics["server"]["cpu_pct"] > 80:
            issues.append({"severity": "high", "issue": "CPU usage high", "value": metrics["server"]["cpu_pct"]})
        
        if metrics["database"]["slow_queries_per_min"] > 10:
            issues.append({"severity": "medium", "issue": "Too many slow queries"})
        
        if metrics["wordpress"]["autoloaded_options_kb"] > 1000:
            issues.append({"severity": "medium", "issue": "Autoloaded options too large"})
        
        if metrics["performance"]["cache_hit_rate_pct"] < 80:
            issues.append({"severity": "medium", "issue": "Cache hit rate low"})
        
        return {
            "status": "healthy" if not issues else "degraded",
            "issues_count": len(issues),
            "issues": issues,
        }
    
    def scaling_recommendation(self, metrics):
        cpu = metrics["server"]["cpu_pct"]
        connections = metrics["server"]["active_connections"]
        
        if cpu > 80 or connections > 200:
            return {"action": "scale_up", "reason": f"CPU: {cpu}%, Connections: {connections}"}
        elif cpu < 20 and connections < 30:
            return {"action": "scale_down", "reason": f"CPU: {cpu}%, Connections: {connections}"}
        else:
            return {"action": "none", "reason": "Resources within normal range"}

monitor = WordPressMonitor()
metrics = monitor.collect_metrics()
health = monitor.check_health(metrics)
scaling = monitor.scaling_recommendation(metrics)

print("Metrics:", json.dumps(metrics["performance"], indent=2))
print("Health:", json.dumps(health, indent=2))
print("Scaling:", json.dumps(scaling, indent=2))

การนำความรู้ไปประยุกต์ใช้งานจริง

แหล่งเรียนรู้ที่แนะนำ ได้แก่ Official Documentation ที่อัพเดทล่าสุดเสมอ Online Course จาก Coursera Udemy edX ช่อง YouTube คุณภาพทั้งไทยและอังกฤษ และ Community อย่าง Discord Reddit Stack Overflow ที่ช่วยแลกเปลี่ยนประสบการณ์กับนักพัฒนาทั่วโลก

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

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

A: ใช่ Block Theme เร็วกว่าเพราะใช้ HTML-based templates แทน PHP templates ลด PHP processing time 30-50%, theme.json จัดการ styles แทน CSS files จำนวนมาก, block rendering optimize แล้วใน WordPress core, ไม่ต้องใช้ page builders (Elementor, Divi) ที่เพิ่ม overhead มาก ในการ benchmark Block Theme (Twenty Twenty-Four) TTFB เฉลี่ย 150ms เทียบกับ Classic Theme + Elementor ที่ 400-600ms

Q: WordPress รองรับ traffic เท่าไหร?

A: ขึ้นกับ server specs และ optimization ไม่มี cache server 4 vCPU รองรับ 50-100 req/s, มี page cache (Nginx FastCGI) รองรับ 500-2000 req/s, มี CDN (Cloudflare APO) รองรับ 10,000+ req/s ตัวอย่าง WordPress.com รองรับ 50,000+ req/s TechCrunch ใช้ WordPress VIP รองรับล้าน pageviews/day ข้อจำกัดหลักคือ database ถ้า optimize cache ดี WordPress scale ได้มาก

Q: Cloudflare APO คุ้มไหม?

A: คุ้มมาก $5/month สำหรับ automatic page caching ที่ edge ลด TTFB จาก 300-500ms เหลือ 30-80ms, ลด origin requests 80-90%, auto purge เมื่อ update content ไม่ต้อง config อะไรมาก เหมาะสำหรับ WordPress ทุกขนาด ถ้า traffic น้อยก็ยังคุ้มเพราะ $5 ถูกมาก ถ้า traffic มากยิ่งคุ้มเพราะลด server costs ได้มาก

Q: ควรใช้ managed WordPress hosting ไหม?

A: ขึ้นกับทีมและ budget Managed hosting (Kinsta, WP Engine, Cloudways) ข้อดี auto scaling, auto backup, security patches, support ข้อเสีย ราคาสูงกว่า ($30-300+/month) Self-managed (VPS + optimize เอง) ข้อดี ราคาถูก ($5-50/month), control เต็มที่ ข้อเสีย ต้องดูแลเอง สำหรับ business site ที่ revenue สำคัญแนะนำ managed hosting สำหรับ side project หรือ blog แนะนำ VPS + Cloudflare APO

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

WordPress Block Theme Home Lab Setupอ่านบทความ → WordPress Block Theme Best Practices ที่ต้องรู้อ่านบทความ → WordPress Block Theme SaaS Architectureอ่านบทความ → WordPress Block Theme Data Pipeline ETLอ่านบทความ → Segment Routing Scaling Strategy วิธี Scaleอ่านบทความ →

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