PHPackages                             highperapp/zero-downtime - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. highperapp/zero-downtime

ActiveLibrary[HTTP &amp; Networking](/categories/http)

highperapp/zero-downtime
========================

Zero-downtime deployment and hot reload for HighPer Framework with WebSocket connection migration

1.0.1(9mo ago)052MITPHPPHP ^8.3|^8.4

Since Jul 6Pushed 9mo agoCompare

[ Source](https://github.com/highperapp/zero-downtime)[ Packagist](https://packagist.org/packages/highperapp/zero-downtime)[ RSS](/packages/highperapp-zero-downtime/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (2)

HighPer Zero-Downtime Reload System
===================================

[](#highper-zero-downtime-reload-system)

Complete zero-downtime deployment and hot reload system for HighPer Framework with WebSocket connection migration support across HTTP/1.1, HTTP/2 (RFC 8441), and HTTP/3 protocols.

🚀 Features
----------

[](#-features)

### **WebSocket Protocol Support**

[](#websocket-protocol-support)

- ✅ **HTTP/1.1 WebSocket** - RFC 6455 compliant via Amp WebSocket
- ✅ **HTTP/2 WebSocket** - RFC 8441 implementation with CONNECT method
- ✅ **HTTP/3 WebSocket** - QUIC-based WebSocket tunneling

### **Zero-Downtime Strategies**

[](#zero-downtime-strategies)

- 🔵🟢 **Blue-Green Deployment** - Complete worker replacement
- 🔄 **Rolling Deployment** - Gradual worker replacement
- 🤝 **Socket Handoff** - Master process handoff with FD transfer

### **Connection Migration**

[](#connection-migration)

- 📦 **State Serialization** - Protocol-specific connection state capture
- 🔄 **Cross-Protocol Support** - HTTP/1.1 ↔ HTTP/2 ↔ HTTP/3 migration
- ⚡ **Compression &amp; Encryption** - Optimized state transfer

### **Request Buffering**

[](#request-buffering)

- 🔄 **Proxy-Level Queuing** - Prevents request loss during transitions
- 👥 **Worker-Specific Buffers** - Granular request routing
- 📊 **Overflow Strategies** - Reject, evict oldest, or compress
- 🏷️ **Priority Headers** - Request prioritization support

📋 Installation
--------------

[](#-installation)

```
composer require highperapp/zero-downtime
```

⚙️ Configuration
----------------

[](#️-configuration)

### Environment Variables

[](#environment-variables)

```
# Zero-Downtime Configuration
ENABLE_ZERO_DOWNTIME=true
ZERO_DOWNTIME_STRATEGY=blue-green  # blue-green|rolling|socket-handoff

# Connection Migration
ENABLE_CONNECTION_MIGRATION=true
CONNECTION_SERIALIZATION_FORMAT=json
CONNECTION_COMPRESSION=true
CONNECTION_STATE_PATH=/tmp/highper-connection-states

# Request Buffering
ENABLE_REQUEST_BUFFERING=true
REQUEST_BUFFER_SIZE_MB=10
REQUEST_BUFFER_TIME=30
REQUEST_OVERFLOW_STRATEGY=reject  # reject|oldest|compress

# Worker Management
WORKER_COUNT=4
GRACEFUL_SHUTDOWN_TIMEOUT=30
AUTO_RESTART_WORKERS=true
MAX_WORKER_MEMORY_MB=128

# Socket Handoff
HANDOFF_SOCKET_PATH=/tmp/highper-socket-handoff
HANDOFF_TIMEOUT=30
SOCKET_REUSE_PORT=true
```

🔧 Usage
-------

[](#-usage)

### Basic Integration

[](#basic-integration)

```
use HighPerApp\HighPer\ZeroDowntime\ZeroDowntimeBootstrap;
use HighPerApp\HighPer\Framework\Contracts\ApplicationInterface;
use Psr\Log\LoggerInterface;

// Initialize in your application bootstrap
$zeroDowntime = new ZeroDowntimeBootstrap($app, $logger, [
    'reload_strategy' => 'blue-green',
    'enable_connection_migration' => true,
    'enable_request_buffering' => true,
    'worker_count' => 4,
    'graceful_shutdown_timeout' => 30
]);

// Trigger zero-downtime reload
posix_kill(posix_getpid(), SIGHUP);

// Get reload result
$result = $zeroDowntime->performZeroDowntimeReload();
echo "Migrated {$result['migrated_connections']} connections";
echo "Replayed {$result['replayed_requests']} requests";
```

### Service Provider Integration

[](#service-provider-integration)

The package includes a service provider for automatic integration:

```
// In your application configuration
'providers' => [
    HighPerApp\HighPer\ZeroDowntime\ZeroDowntimeServiceProvider::class,
]
```

### Manual Component Usage

[](#manual-component-usage)

```
use HighPerApp\HighPer\ZeroDowntime\ConnectionMigration\ConnectionStateSerializer;
use HighPerApp\HighPer\ZeroDowntime\RequestQueue\ProxyRequestQueue;
use HighPerApp\HighPer\WebSocket\WebSocketConnection;
use HighPerApp\HighPer\Websockets\Http2WebSocketConnection;

// Connection serialization with active state management
$serializer = new ConnectionStateSerializer($logger, [
    'compression_enabled' => true,
    'state_storage_path' => '/tmp/highper-connection-states'
]);

// Register connections
$serializer->registerConnection('conn1', $webSocketConnection, 'http1_websocket');
$serializer->registerConnection('conn2', $http2WebSocketConnection, 'http2_websocket');

// Manage connection states for zero-downtime optimization
$serializer->markConnectionActive('conn1');  // O(1) performance
$serializer->markConnectionIdle('conn2');

// Serialize only active connections for priority migration
$activeStates = $serializer->serializeActiveConnections();
echo "Active connections: " . $serializer->getActiveConnectionCount();

// Serialize all connections
$allStates = $serializer->serializeAllConnections();

// Migrate connections to new workers
$workers = [['pid' => 1234], ['pid' => 1235]];
$migrationResult = $serializer->migrateConnectionsToWorkers($workers, $activeStates);

// Request buffering with worker-specific handling
$queue = new ProxyRequestQueue($logger, [
    'max_buffer_size_mb' => 10,
    'max_buffer_time_seconds' => 30,
    'overflow_strategy' => 'reject',
    'priority_headers' => ['x-priority', 'x-urgent']
]);

// Global request buffering
$queue->startBuffering();
$queue->bufferRequest([
    'method' => 'POST',
    'uri' => '/api/data',
    'headers' => ['x-priority' => '1'],
    'body' => json_encode(['data' => 'important'])
]);

// Worker-specific buffering
$workerPid = 1234;
$queue->startWorkerBuffering($workerPid);
$queue->bufferRequest($request, $workerPid);

// Replay buffered requests
$replayResult = $queue->replayBufferedRequests($workers);
echo "Replayed {$replayResult['replayed_requests']} requests in {$replayResult['replay_time_ms']}ms";

// Get queue statistics
$stats = $queue->getStats();
echo "Buffer utilization: {$stats['global_buffer']['size_bytes']} bytes";
```

🌐 WebSocket Migration
---------------------

[](#-websocket-migration)

### HTTP/2 WebSocket (RFC 8441)

[](#http2-websocket-rfc-8441)

```
use EaseAppPHP\HighPer\Websockets\Http2WebSocketHandler;

$handler = new Http2WebSocketHandler($logger, [
    'enable_compression' => true,
    'max_frame_size' => 65536
]);

// Handles CONNECT method with :protocol pseudo-header
```

### Connection State Serialization

[](#connection-state-serialization)

```
// Automatic protocol detection and serialization
$connectionStates = $serializer->serializeAllConnections();

// Each state includes:
// - Connection ID and protocol type
// - Remote address and attributes
// - Protocol-specific state (HTTP/2 stream ID, HTTP/3 QUIC state)
// - Frame buffers and compression context
```

🚦 Deployment Strategies
-----------------------

[](#-deployment-strategies)

### Blue-Green Deployment

[](#blue-green-deployment)

```
# Trigger blue-green reload
kill -HUP
```

1. **Start request queuing** - Buffer incoming requests
2. **Serialize connections** - Capture all WebSocket states
3. **Spawn green workers** - New worker processes
4. **Transfer sockets** - Hand off listening sockets
5. **Migrate connections** - Restore WebSocket states
6. **Replay requests** - Process buffered requests
7. **Terminate blue workers** - Clean shutdown

### Rolling Deployment

[](#rolling-deployment)

Individual worker replacement with minimal disruption:

```
# Set rolling strategy
export ZERO_DOWNTIME_STRATEGY=rolling
kill -HUP
```

### Socket Handoff

[](#socket-handoff)

Master process replacement with complete state transfer:

```
# Set socket handoff strategy
export ZERO_DOWNTIME_STRATEGY=socket-handoff
kill -HUP
```

🏥 Health Monitoring
-------------------

[](#-health-monitoring)

### Health Check Endpoints

[](#health-check-endpoints)

```
# Zero-downtime status
GET /_zero-downtime/status

# Test connection migration
POST /_zero-downtime/test-migration

# Flush request queue
POST /_zero-downtime/flush-queue
```

### Statistics API

[](#statistics-api)

```
$stats = $zeroDowntime->getStats();
/*
{
    "reload_in_progress": false,
    "strategy": "blue-green",
    "active_connections": 150,
    "buffered_requests": 0,
    "worker_stats": {...},
    "socket_stats": {...}
}
*/
```

🧪 Testing
---------

[](#-testing)

Run the comprehensive test suite:

```
# Install dependencies
composer install

# Run all tests
./vendor/bin/phpunit

# Run specific test groups
./vendor/bin/phpunit --group unit
./vendor/bin/phpunit --group integration
./vendor/bin/phpunit --group performance
./vendor/bin/phpunit --group concurrency

# Run with coverage
./vendor/bin/phpunit --coverage-html coverage

# Run static analysis
./vendor/bin/phpstan analyse src --level=max

# Fix code style
./vendor/bin/php-cs-fixer fix
```

### Test Coverage

[](#test-coverage)

**Unit Tests (43 tests)**

- ✅ ConnectionStateSerializer - Active/idle state management
- ✅ ProxyRequestQueue - Request buffering and prioritization
- ✅ ZeroDowntimeBootstrap - Deployment orchestration
- ✅ Worker management and socket handling

**Integration Tests**

- ✅ End-to-end zero-downtime reload workflows
- ✅ Connection migration with request buffering coordination
- ✅ Blue-green deployment strategy validation
- ✅ Health monitoring and graceful shutdown

**Performance Tests**

- ✅ 1000+ connection serialization (&lt; 1 second)
- ✅ 10,000+ request buffering (&lt; 5 seconds)
- ✅ Memory stability during extended operations
- ✅ Linear scaling validation

**Concurrency Tests**

- ✅ Thread-safe connection registration
- ✅ Race condition protection
- ✅ Concurrent reload isolation
- ✅ Worker handoff atomicity

🎛️ Advanced Configuration
-------------------------

[](#️-advanced-configuration)

### Custom Connection Migration

[](#custom-connection-migration)

```
// Register custom connection types
$serializer->registerConnection('custom_conn', $connection, 'custom_protocol');

// Implement custom serialization
class CustomConnectionSerializer extends ConnectionStateSerializer
{
    protected function serializeCustomProtocolState($connection): array
    {
        // Custom serialization logic
        return [
            'custom_state' => $connection->getCustomState(),
            'protocol_version' => $connection->getProtocolVersion()
        ];
    }
}
```

### Request Priority Headers

[](#request-priority-headers)

```
# Configure priority headers
export REQUEST_PRIORITY_HEADERS=x-priority,x-urgent,x-critical

# In requests
curl -H "x-priority: 1" -H "x-urgent: true" http://localhost:8080/api
```

### Worker Auto-Restart

[](#worker-auto-restart)

```
# Configure auto-restart limits
export AUTO_RESTART_WORKERS=true
export WORKER_RESPAWN_LIMIT=5
export WORKER_RESPAWN_WINDOW=300
```

🔒 Security Considerations
-------------------------

[](#-security-considerations)

### Connection State Security

[](#connection-state-security)

```
// Enable encryption for sensitive connection data
$serializer = new ConnectionStateSerializer($logger, [
    'encryption_enabled' => true,
    'encryption_key' => getenv('CONNECTION_STATE_KEY'),
    'compression_enabled' => true
]);
```

### Socket Path Permissions

[](#socket-path-permissions)

```
# Secure socket handoff directory
sudo mkdir -p /var/run/highper
sudo chown www-data:www-data /var/run/highper
sudo chmod 750 /var/run/highper

# Set in configuration
export HANDOFF_SOCKET_PATH=/var/run/highper/socket-handoff
```

### Request Buffer Limits

[](#request-buffer-limits)

```
// Configure secure buffer limits
$queue = new ProxyRequestQueue($logger, [
    'max_buffer_size_mb' => 10,        // Prevent memory exhaustion
    'max_requests_per_buffer' => 1000, // Limit buffer size
    'max_buffer_time_seconds' => 30,   // Prevent indefinite buffering
    'buffer_to_disk' => false          // Avoid disk-based attacks
]);
```

### Worker Process Isolation

[](#worker-process-isolation)

```
# Configure process limits
export MAX_WORKER_MEMORY_MB=128
export WORKER_CPU_LIMIT=80
export WORKER_FILE_DESCRIPTOR_LIMIT=1024

# Use systemd for additional isolation
sudo systemctl edit highper-app --force
```

📊 Performance Metrics
---------------------

[](#-performance-metrics)

### Benchmarked Performance

[](#benchmarked-performance)

**Connection Migration Performance**

```
HTTP/1.1 WebSocket:  ~1.0ms per connection (baseline)
HTTP/2 WebSocket:    ~1.5ms per connection (+50% overhead)
HTTP/3 WebSocket:    ~2.0ms per connection (+100% overhead)

Active Connection Lookup: O(1) - ~0.001ms per lookup
Batch Migration (1000 conns): ~1.2 seconds total

```

**Request Buffering Performance**

```
Memory Usage:         ~2KB per buffered request
Buffering Rate:       ~50,000 requests/second
Serialization Rate:   ~281,000 connections/second
Replay Speed:         ~10,000 requests/second
Priority Sorting:     ~500ms for 5,000 requests

```

**Zero-Downtime Reload Metrics**

```
Blue-Green Reload:    ~2-5 seconds (depends on connection count)
Rolling Reload:       ~10-30 seconds (gradual replacement)
Socket Handoff:       ~1-3 seconds (fastest method)

Memory Overhead:      getStats();

echo "Active connections: {$stats['active_connections']}";
echo "Memory usage: {$stats['memory_usage_mb']}MB";
echo "Uptime: {$stats['uptime_seconds']} seconds";

// Health status monitoring
$health = $bootstrap->getHealthStatus();
echo "Status: {$health['status']}";  // healthy|reloading|degraded
echo "Component status: " . json_encode($health['components']);
```

🐛 Troubleshooting
-----------------

[](#-troubleshooting)

### Common Issues

[](#common-issues)

**Connection Migration Fails**

```
# Check connection state path permissions
ls -la /tmp/highper-connection-states

# Verify protocol support
grep -r "http2_websocket" /var/log/highper/
```

**Request Buffer Overflow**

```
# Increase buffer size
export REQUEST_BUFFER_SIZE_MB=50

# Change overflow strategy
export REQUEST_OVERFLOW_STRATEGY=oldest
```

**Worker Handoff Timeout**

```
# Increase timeout
export HANDOFF_TIMEOUT=60

# Check socket permissions
ls -la /tmp/highper-socket-handoff*
```

📚 API Reference
---------------

[](#-api-reference)

### ZeroDowntimeBootstrap

[](#zerodowntimebootstrap)

```
class ZeroDowntimeBootstrap
{
    // Deployment operations
    public function performZeroDowntimeReload(): array;              // Trigger hot reload
    public function performGracefulShutdown(): array;                // Graceful shutdown
    public function testConnectionMigration(): void;                 // Test migration

    // Status and monitoring
    public function getStats(): array;                               // System statistics
    public function getHealthStatus(): array;                        // Health check
    public function isReloadInProgress(): bool;                      // Check reload status
}
```

### ConnectionStateSerializer

[](#connectionstateserializer)

```
class ConnectionStateSerializer
{
    // Connection management
    public function registerConnection(string $id, object $connection, string $protocol): void;
    public function unregisterConnection(string $connectionId): void;
    public function hasConnection(string $connectionId): bool;

    // Active state management (O(1) performance)
    public function markConnectionActive(string $connectionId): void;
    public function markConnectionIdle(string $connectionId): void;
    public function markConnectionClosing(string $connectionId): void;
    public function isConnectionActive(string $connectionId): bool;

    // Serialization operations
    public function serializeAllConnections(): array;                // All connections
    public function serializeActiveConnections(): array;             // Active only (priority)
    public function serializeWorkerConnections(int $workerPid): array;

    // Migration operations
    public function migrateConnectionsToWorkers(array $workers, array $states): array;
    public function migrateWorkerConnections(array $newWorker, array $connectionStates): void;

    // Statistics and validation
    public function getActiveConnectionCount(): int;                 // O(1) performance
    public function getTotalConnectionCount(): int;
    public function getConnectionStats(): array;
    public function validateStates(array $states): array;

    // Compression utilities
    public function compressStates(array $states): string;
    public function decompressStates(string $compressedData): array;
}
```

### ProxyRequestQueue

[](#proxyrequestqueue)

```
class ProxyRequestQueue
{
    // Buffer management
    public function startBuffering(): void;                          // Global buffering
    public function stopBuffering(): void;
    public function startWorkerBuffering(int $workerPid): void;      // Worker-specific
    public function stopWorkerBuffering(int $workerPid): void;

    // Request operations
    public function bufferRequest($request, ?int $targetWorkerPid = null): bool;
    public function replayBufferedRequests(array $newWorkers): array;
    public function replayWorkerRequests(array $newWorker, int $oldWorkerPid): void;

    // Queue management
    public function flush(): void;                                   // Emergency flush
    public function flushBuffer(): array;                            // Get and clear
    public function getBufferedRequests(): array;                    // Priority sorted
    public function getRequestsForWorker(string $workerId): array;
    public function getExpiredRequests(): array;

    // Status and statistics
    public function getBufferedRequestCount(): int;
    public function isBufferingEnabled(): bool;
    public function getBufferStats(): array;
    public function getPerformanceMetrics(): array;
    public function getStats(): array;
}
```

### Response Formats

[](#response-formats)

**performZeroDowntimeReload() Response:**

```
[
    'reload_successful' => true,
    'migrated_connections' => 150,
    'replayed_requests' => 45,
    'strategy' => 'blue-green',
    'duration_ms' => 2340.50
]
```

**getHealthStatus() Response:**

```
[
    'status' => 'healthy',  // healthy|reloading|degraded
    'components' => [
        'connection_migration' => [
            'status' => 'healthy',
            'active_connections' => 150
        ],
        'request_buffering' => [
            'status' => 'idle',
            'buffered_requests' => 0
        ]
    ],
    'uptime_seconds' => 3600.45,
    'memory_usage_mb' => 45.2
]
```

🤝 Contributing
--------------

[](#-contributing)

1. Fork the repository
2. Create feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open Pull Request

🔧 Requirements
--------------

[](#-requirements)

- **PHP**: ^8.3|^8.4
- **Extensions**: ext-pcntl, ext-posix, ext-sockets
- **Dependencies**: highperapp/websockets ^1.1
- **Framework**: Compatible with HighPer Framework
- **Environment**: Linux/Unix systems (process management)

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

- **RFC 8441** - WebSocket over HTTP/2 specification
- **Amp Framework** - Asynchronous PHP components
- **QUIC Protocol** - HTTP/3 transport layer
- **HighPer Framework** - High-performance PHP framework

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance56

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~21 days

Total

2

Last Release

295d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dbe04e216b4fb74f076a82bb6bd06f96faa4066089b33082c43f8c9cf184efbf?d=identicon)[raghuveer](/maintainers/raghuveer)

---

Top Contributors

[![raghuveer](https://avatars.githubusercontent.com/u/999229?v=4)](https://github.com/raghuveer "raghuveer (2 commits)")

---

Tags

phphttp2websockethttp3hot-reloadzero-downtimequichighperconnection-migration

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/highperapp-zero-downtime/health.svg)

```
[![Health](https://phpackages.com/badges/highperapp-zero-downtime/health.svg)](https://phpackages.com/packages/highperapp-zero-downtime)
```

###  Alternatives

[openswoole/core

Openswoole core library

181.1M32](/packages/openswoole-core)[basement-chat/basement-chat

Add a real-time chat widget to your Laravel application.

4983.9k](/packages/basement-chat-basement-chat)[swoole/etcd-client

Grpc PHP Client base on Swoole Http2 Coroutine

1973.2k1](/packages/swoole-etcd-client)[hyperf/websocket-server

A websocket server library for Hyperf.

12488.7k25](/packages/hyperf-websocket-server)[swoft/websocket-server

swoft websocket server component

16134.1k5](/packages/swoft-websocket-server)[hemiframe/php-websocket

PHP WebSocket server and client library

4911.0k](/packages/hemiframe-php-websocket)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
