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:
src/protocol/protocol.zig: IncreaseMAX_MESSAGE_SIZEfrom 65535 to 2MB (2097152)src/core/limits.zig: Verify configurable limits support larger sizes (already 64MB)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:
src/files/manager.zig: Add aPieceBufferPoolstruct that pre-allocates buffers- Use existing
core/buffer.zigBufferPoolpattern with acquire/release API - Pool size: 128 buffers of max_piece_size each
- Integrate into
handlePieceDataandhandlePieceRequest
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:
src/files/file.zig(FileWriter): AddpwriteAllmethod for position-independent writessrc/files/download.zig(DownloadManager): Use pwrite instead of seek+writesrc/files/manager.zig: RestructurehandlePieceData:- 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:
-
Create
src/files/verification_pool.zig:- Thread pool with N workers (default: CPU count)
- Work queue for pending verifications
- Callback mechanism for completion notification
-
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 -
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:
-
Create pipelined architecture:
Network Recv → Decode Queue → Write Queue → Verify Queue → Complete ↓ ↓ ↓ ↓ [Thread 1] [Thread 2] [Thread 3] [Thread 4+] -
src/files/manager.zig: AddPieceProcessingPipeline:DecodeWorker: Parse incoming piece messagesWriteWorker: Handle disk I/O (can have multiple)VerifyWorker: SHA-256 verification (reuse Phase 4 pool)
-
Use lock-free queues (or mutex-protected with minimal hold time):
- Leverage existing
AsyncMessageProcessorpattern fromprotocol/handler.zig - Each stage processes independently
- Leverage existing
-
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
-
Update
examples/multi_peer_download_test.zig:- Add command-line args for piece size, peer count
- Add per-peer throughput tracking
- Add latency percentiles
-
Create benchmark comparing:
- Before: Current implementation
- After: All optimizations enabled
-
Verify correctness:
- Run existing tests
- Stress test with many concurrent peers
- Verify file integrity under load
Implementation Order
- Phase 1 (Message size) - Low risk, immediate benefit
- Phase 3 (pwrite outside mutex) - Medium complexity, high impact
- Phase 2 (Buffer pool) - Low complexity, reduces allocations
- Phase 4 (Parallel SHA-256) - Medium complexity, unblocks CPU
- Phase 5 (Pipeline) - High complexity, maximum parallelism
- 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