Files
zigp2p/architecture/PERFORMANCE_OPTIMIZATION_PLAN.md
2026-02-06 21:03:59 -03:00

5.6 KiB

P2P Performance Optimization Plan

Current State

  • Single-peer: 39 MB/s
  • Multi-peer (10 peers): 82.4 MB/s (only 2.1x speedup, not 10x)

Goal

Achieve near-linear scaling with multiple peers (targeting 300+ MB/s with 10 peers).


Phase 1: Increase Message/Piece Size Limits

Problem: Protocol MAX_MESSAGE_SIZE = 65535 (64KB-1) in protocol.zig limits effective piece sizes.

Changes:

  1. src/protocol/protocol.zig: Increase MAX_MESSAGE_SIZE from 65535 to 2MB (2097152)
  2. src/core/limits.zig: Verify configurable limits support larger sizes (already 64MB)
  3. examples/multi_peer_download_test.zig: Test with 1MB pieces

Files: protocol.zig, limits.zig, test files


Phase 2: Pre-allocated Buffer Pool for Piece Data

Problem: Each piece transfer allocates/frees memory, causing allocation overhead.

Changes:

  1. src/files/manager.zig: Add a PieceBufferPool struct that pre-allocates buffers
  2. Use existing core/buffer.zig BufferPool pattern with acquire/release API
  3. Pool size: 128 buffers of max_piece_size each
  4. Integrate into handlePieceData and handlePieceRequest

Files: manager.zig, potentially new src/files/buffer_pool.zig


Phase 3: Move Disk Writes Outside Mutex (pwrite)

Problem: sessions_mutex is held during disk writes in handlePieceData Phase 4.

Changes:

  1. src/files/file.zig (FileWriter): Add pwriteAll method for position-independent writes
  2. src/files/download.zig (DownloadManager): Use pwrite instead of seek+write
  3. src/files/manager.zig: Restructure handlePieceData:
    • Hold mutex only for session lookup and state updates
    • Perform disk write OUTSIDE mutex using pwrite with calculated offset
    • Re-acquire mutex only for completion bookkeeping

Implementation:

// Before (inside mutex):
session.download_manager.writePieceData(piece_index, data);

// After (mutex-free disk I/O):
const offset = piece_index * piece_size;
const file_handle = session.download_manager.getFileHandle();
// Release mutex
mutex.unlock();
// Write without mutex
_ = file_handle.pwriteAll(data, offset);
// Re-acquire for bookkeeping
mutex.lock();
session.markPieceComplete(piece_index);

Files: file.zig, download.zig, manager.zig


Phase 4: Parallel SHA-256 Verification with Thread Pool

Problem: SHA-256 verification is CPU-bound and single-threaded, blocking piece processing.

Changes:

  1. Create src/files/verification_pool.zig:

    • Thread pool with N workers (default: CPU count)
    • Work queue for pending verifications
    • Callback mechanism for completion notification
  2. src/files/hash.zig: Add async verification API:

    pub fn queueVerification(
        pool: *VerificationPool,
        piece_index: u32,
        data: []const u8,
        expected_hash: [32]u8,
        callback: VerificationCallback,
    ) void
    
  3. src/files/manager.zig: Use pool for verification:

    • Queue piece for verification instead of blocking
    • Mark piece as "pending_verification" state
    • Complete piece on verification callback

Files: New verification_pool.zig, hash.zig, manager.zig


Phase 5: Multi-threaded Piece Processing Pipeline

Problem: Piece processing is sequential - one piece at a time per session.

Changes:

  1. Create pipelined architecture:

    Network Recv → Decode Queue → Write Queue → Verify Queue → Complete
         ↓              ↓              ↓              ↓
     [Thread 1]    [Thread 2]    [Thread 3]    [Thread 4+]
    
  2. src/files/manager.zig: Add PieceProcessingPipeline:

    • DecodeWorker: Parse incoming piece messages
    • WriteWorker: Handle disk I/O (can have multiple)
    • VerifyWorker: SHA-256 verification (reuse Phase 4 pool)
  3. Use lock-free queues (or mutex-protected with minimal hold time):

    • Leverage existing AsyncMessageProcessor pattern from protocol/handler.zig
    • Each stage processes independently
  4. src/files/download.zig: Add atomic piece state tracking:

    const PieceState = enum(u8) {
        missing,
        requested,
        received,
        writing,
        verifying,
        complete,
        failed,
    };
    piece_states: []std.atomic.Value(PieceState),
    

Files: manager.zig, download.zig, potentially new pipeline.zig


Phase 6: Testing and Benchmarking

  1. Update examples/multi_peer_download_test.zig:

    • Add command-line args for piece size, peer count
    • Add per-peer throughput tracking
    • Add latency percentiles
  2. Create benchmark comparing:

    • Before: Current implementation
    • After: All optimizations enabled
  3. Verify correctness:

    • Run existing tests
    • Stress test with many concurrent peers
    • Verify file integrity under load

Implementation Order

  1. Phase 1 (Message size) - Low risk, immediate benefit
  2. Phase 3 (pwrite outside mutex) - Medium complexity, high impact
  3. Phase 2 (Buffer pool) - Low complexity, reduces allocations
  4. Phase 4 (Parallel SHA-256) - Medium complexity, unblocks CPU
  5. Phase 5 (Pipeline) - High complexity, maximum parallelism
  6. Phase 6 (Testing) - Validate all changes

Expected Results

Phase Expected Throughput Scaling Factor
Current 82 MB/s (10 peers) 2.1x
+Phase 1 100 MB/s 2.5x
+Phase 3 150 MB/s 4x
+Phase 2,4 250 MB/s 6x
+Phase 5 350+ MB/s 9x+

Risk Mitigation

  • Each phase is independently testable
  • Existing tests must pass after each phase
  • Performance regression tests between phases
  • Can roll back individual phases if issues arise