easythemestore

How to Use WebSockets for Real-Time Inventory Updates in WooCommerce

How to Use WebSockets for Real-Time Inventory Updates in WooCommerce

A fast, real-time inventory system prevents overselling and improves customer trust. Traditional WooCommerce inventory checks rely on page refreshes or slow AJAX polling, which can delay stock updates by seconds.

WebSockets enable instant, bi-directional communication between your server and customers’ browsers, showing stock changes the moment they happen—without reloading the page.

This guide covers how to implement WebSockets in WooCommerce for live inventory tracking with minimal performance impact.


Why Use WebSockets Instead of AJAX Polling?

MethodLatencyServer LoadReal-Time Updates
AJAX PollingHigh (1-5s)Heavy (repeated requests)❌ Delayed
WebSocketsInstant (~50ms)Light (persistent connection)✅ True real-time

Benefits of WebSockets for WooCommerce Inventory

✔ Prevents overselling (sync stock across all sessions instantly)
✔ Better UX (customers see stock changes live)
✔ Reduces server load (no constant AJAX requests)
✔ Works for high-traffic stores (scales better than polling)


3 Ways to Implement WebSockets in WooCommerce

1. Using Pusher (Easiest SaaS Solution)

Pusher Channels is a hosted WebSocket service that integrates easily with WooCommerce.

Setup Steps:

  1. Install the Pusher PHP SDK

    bash
    composer require pusher/pusher-php-server
  2. Trigger stock updates on product changes

    php
    add_action('woocommerce_update_product', 'send_stock_update_via_pusher', 10, 1);
    function send_stock_update_via_pusher($product_id) {
        $product = wc_get_product($product_id);
        $pusher = new Pusher\Pusher(APP_KEY, APP_SECRET, APP_ID);
        $pusher->trigger('inventory-channel', 'stock-update', [
            'product_id' => $product_id,
            'stock' => $product->get_stock_quantity()
        ]);
    }
  3. Frontend JavaScript to listen for updates

    javascript
    const pusher = new Pusher('YOUR_APP_KEY');
    const channel = pusher.subscribe('inventory-channel');
    channel.bind('stock-update', (data) => {
        document.querySelector(`.stock[data-product-id="${data.product_id}"]`).textContent = data.stock;
    });

2. Self-Hosted with Ratchet (PHP WebSocket Server)

For stores needing full control, Ratchet is a PHP WebSocket library.

How to Set Up:

  1. Run a WebSocket server (separate from WordPress)

    php
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new class implements MessageComponentInterface {
                    public function onMessage(ConnectionInterface $conn, $msg) {
                        // Broadcast inventory updates to all clients
                        foreach ($this->clients as $client) {
                            $client->send($msg);
                        }
                    }
                }
            )
        ),
        8080
    );
    $server->run();
  2. Connect WooCommerce to the WebSocket server

    php
    add_action('woocommerce_product_set_stock', 'push_stock_to_ws_server');
    function push_stock_to_ws_server($product) {
        $context = new ZMQContext();
        $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'stock_pusher');
        $socket->connect("tcp://localhost:8080");
        $socket->send(json_encode([
            'product_id' => $product->get_id(),
            'stock' => $product->get_stock_quantity()
        ]));
    }

3. Hybrid Approach: WP REST API + Socket.IO

For Node.js-friendly setups, use Socket.IO with WordPress REST API.

  1. Node.js WebSocket server

    javascript
    const io = require('socket.io')(3000);
    io.on('connection', (socket) => {
        socket.on('stock-update', (data) => {
            io.emit('inventory-change', data);
        });
    });
  2. WooCommerce hooks to emit changes

    php
    add_action('woocommerce_reduce_order_stock', 'notify_node_server');
    function notify_node_server($order) {
        wp_remote_post('http://localhost:3000/stock-update', [
            'body' => json_encode(['order_items' => $order->get_items()])
        ]);
    }

Optimizing WebSockets for Performance

  • Use a dedicated subdomain (wss://socket.yourstore.com)
  • Compress WebSocket messages (msgpack instead of JSON)
  • Implement reconnection logic (avoid WebSocket drops)
  • Rate-limit updates (batch changes if needed)

Final Thoughts

WebSockets eliminate stock sync delays, improving customer experience and reducing support tickets from overselling.

Best option for most stores: Pusher (easiest setup)
For developers: Ratchet or Socket.IO (full control)

🚀 Implement WebSockets today and never worry about outdated stock displays again!